How to separate list input by comma? - python

So I'm making a A1Z26 cipher decoder where I could enter the numbers in and it'll return a corresponding letter, e.g. 8,5,12,12,0 --> h,e,l,l,o.
However, I'm having trouble figuring out how to make python take each number as input as opposed to splitting them into digits.
Any help would be appreciated. Thanks
EDIT:
Here's the code I've written so far:`
dic = {dictionary that translates numbers to letters}
mid = []
output = []
input = raw_input("Enter the code here: ")
splitinput = list(input)
for i in splitinput:
if i != ",":
mid.append(i)
mid = [int(i) for i in buffer]
for i in mid:
output.append(dic[i])
print output
So for it to stop splitting each number into digits I would need to use something other than the list function.

Something like this:
myint = 123456789
mystr = str(myint)
print(','.join(mystr[::2]))

Alright, I found it. This is the code that gives me the desired output if anyone will be interested:
inv_alphabet = {contains the mapping of each number to letter}
output = []
code_input = str(raw_input("Enter your cipher here: "))
split_code = code_input.split(",")
split_code = [int(i) for i in split_code]
for i in split_code:
output.append(inv_alphabet[i])
print output

Related

Counting how many times each letter appears in the string

I'm trying to count how many times each letter appears in the string and then display it in a list eg.
The word "hello" would be:
{h:1, e:1, l:2, o:2}
This is my code.
text = input()
dict = {}
for k in range(len(text)):
if text[k] in dict:
count +=1
dict.update({text[k]:count})
else:
count=1
dict.update({text[k]:count})
print(dict)
The code works on smaller words but not for words that are >10
Can someone please point out what is wrong or what I am missing.
You can use the following code to count letter frequencies:
d = {}
for letter in text:
d[letter] = d.get(letter, 0) + 1
print(d)
I've changed your code around a bit that seems to work:
trans = {}
def letterCounter(num):
for ch in num.lower():
if ch in trans.keys():
trans[ch] += 1;
else:
trans[ch] = 1;
print('Counts letters shown in the input:')
for x in sorted(trans):
print(f"Letter \"{x}\": {trans[x]}")
try:
usr = input('Please insert your input & press ENTER to count its letters: ')
letterCounter(usr)
except ValueError:
print('Input must contain a word or sentence')
I know this is a little bit different than what you asked for, but this seems to work very well, and I used www.cologic.dev to do it. It uses code completion to help you learn and code more efficiently.

Printing individual letters in a list

I am writing a program that takes a statement or phrase from a user and converts it to an acronym.
It should look like:
Enter statement here:
> Thank god it's Friday
Acronym : TGIF
The best way I have found to accomplish this is through a list and using .split() to separate each word into its own string and am able to isolate the first letter of the first item, however when I try to modify the program for the following items by changing to print statement to:
print("Acronym :", x[0:][0])
it just ends up printing the entirety of the letters in the first item.
Here's what I have gotten so far, however it only prints the first letter of the first item...
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
print("Acronym :", x[0][0])
Using re.sub with a callback we can try:
inp = "Peas porridge hot"
output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
print(output) # PPH
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
result = ''
for i in x:
word = list(i)
result+=word[0]
print(result)
The code needs to iterate through the .split result. For example, using a list comprehension:
inp = "Thank god its friday"
inp = inp.split()
first_lets = [word[0] for word in inp]

Why is my function not prompting me to enter input?

I’m using Python IDE 3. My goal is this: If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’). I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:
#data
code_text = input('Text: ').lower()
code_skip = int(input('Shift length: '))
code_list = []
#function
def countSkip(text, shift, listt):
i = 0
group = 1
if group <= shift:
for e in text:
#make sure the set starts at the right place
if e.index()+1 < group:
pass
elif shift != 0:
if i = shift:
listt.append(e)
i = 0
i += 1
else:
listt.append(e)
group += 1
Calling the function
countSkip(code_text, code_shift, code_list)
There's a few things stopping your code from working that people have pointed out in the comments. Instead of trying to dissect your code and get that to work, I wrote a much more concise function that will get you the results you're after
def text_splitter(input_text, set_length):
num_sets = int(len(input_text)/set_length)
split_text = ["".join([input_text[(n * num_sets) + m] for n in range(set_length)]) for m in range(num_sets)]
return split_text
text_to_split = input('Text: ').lower()
len_set = int(input('Set Length: '))
text_list = text_splitter(text_to_split, len_set)
Sorry I was struggling to name the variables in an effective manner but the function above uses a list expression to get you the results you need. Keep in mind that if you use say a 7 letter string and ask for sets of length 2, the last letter won't be appended. However this shouldn't be too hard to check and correct. For example you could add this code to the function or around the initial input for the set length:
while len(input_text) % set_length != 0:
set_length = int(input("The text is length " + str(len(input_text)) + " please enter a different set length: "))

Can't call dictionary function. keyError 0

For my comp sci class I was assigned to make an english to pirate dictionary. The user is prompted to enter a sentence which is then translated to pirate but it isn't working and I'm not sure why. Any help would be appreciated.
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate: ")
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
print(b)
Your loop is iterating over range(len(a)), so x will take on an integer value for each individual character in your input. This is off for a couple of reasons:
Your goal is to iterate over words, not characters.
Indexing the dictionary should be done with words, not integers (this is the cause of your error).
Finally, note that .replace() replaces the first occurrence of the searched item in the string. To revise your approach to this problem in a way that still uses that method, consider these two main changes:
Iterate over the keys of the dictionary; the words that could potentially be replaced.
Loop until no such words exist in the input, since replace only does individual changes.
You're iterating over each of the characters in the string input, as the other answer before this has said, replace only replaces the first occurence.
You'd want to do something like this (after you've made your dictionary).
a = input("Please enter a sentence to be translated into pirate: ")
for x in eng2pir:
while x in a:
a = a.replace(x,eng2pir[x])
print(a)
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
because for loop x is int
but eng2pir dict no int key
so output error
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate:\n ")
lst = a.split()
b = ''
for word in lst:
b += eng2pir.get(word, "")
print(b)

Process multiple input values in Python

Hi so I'm very very new to programming so please forgive me if I'm not able to ask with the correct jargon, but I'm writing a simple program for an assignment in which I'm to convert CGS units to SI units
For example:
if num == "1": #Gauss --> Tesla
A=float(raw_input ("Enter value: "))
print "=", A/(1e4), "T"
with this I'm only able to convert one value at a time. Is there a way I can input multiple values, perhaps separated by commas and perform the calculation on all of them simultaneously and spit out another list with the converted values?
You can read in a comma-separated list of numbers from the user (with added whitespace possibly), then split it, strip the excessive white space, and loop over the resulting list, converting each value, putting it in a new list, and then finally outputting that list:
raw = raw_input("Enter values: ")
inputs = raw.split(",")
results = []
for i in inputs:
num = float(i.strip())
converted = num / 1e4
results.append(converted)
outputs = []
for i in results:
outputs.append(str(i)) # convert to string
print "RESULT: " + ", ".join(outputs)
Later, when you're more fluent in Python, you could make it nicer and more compact:
inputs = [float(x.strip()) for x in raw_input("Enter values: ").split(",")]
results = [x / 1e4 for x in inputs]
print "RESULT: " + ", ".join(str(x) for x in results)
or even go as far as (not recommended):
print "RESULT: " + ", ".join(str(float(x.strip()) / 1e4) for x in raw_input("Enter values: ").split(","))
If you want to keep doing that until the user enters nothing, wrap everything like this:
while True:
raw = raw_input("Enter values: ")
if not raw: # user input was empty
break
... # rest of the code
Sure! You'll have to provide some sort of "marker" for when you're done, though. How about this:
if num == '1':
lst_of_nums = []
while True: # infinite loops are good for "do this until I say not to" things
new_num = raw_input("Enter value: ")
if not new_num.isdigit():
break
# if the input is anything other than a number, break out of the loop
# this allows for things like the empty string as well as "END" etc
else:
lst_of_nums.append(float(new_num))
# otherwise, add it to the list.
results = []
for num in lst_of_nums:
results.append(num/1e4)
# this is more tersely communicated as:
# results = [num/1e4 for num in lst_of_nums]
# but list comprehensions may still be beyond you.
If you're trying to enter a bunch of comma-separated values, try:
numbers_in = raw_input("Enter values, separated by commas\n>> ")
results = [float(num)/1e4 for num in numbers_in.split(',')]
Hell if you wanted to list both, construct a dictionary!
numbers_in = raw_input("Enter values, separated by commas\n>> ")
results = {float(num):float(num)/1e4 for num in numbers_in.split(',')}
for CGS,SI in results.items():
print "%.5f = %.5fT" % (CGS, SI)
# replaced in later versions of python with:
# print("{} = {}T".format(CGS,SI))

Categories