I am making an English to Morse code and vise-versa program. I successfully made it translate English to Morse code but am having a trouble translating Morse code to English. Whenever I try to translate Morse code to English, it gives me a TypeError: “text = ''.join(map(trans_back.get, user_input))
TypeError: sequence item 0: expected str instance, NoneType found”.
Here is my code so far. The last section is the part of the code where I am having trouble:
translation = {
"A": ".- ",
"B": "-... ",
"C": "-.-. ",
"D": "-.. ",
"E": ". ",
"F": "..-. ",
"G": "--. ",
"H": ".... ",
"I": ".. ",
"J": ".--- ",
"K": "-.- ",
"L": ".-.. ",
"M": "-- ",
"N": "-. ",
"O": "--- ",
"P": ".--. ",
"Q": "--.- ",
"R": ".-. ",
"S": "... ",
"T": "- ",
"U": "..- ",
"V": "...- ",
"W": ".-- ",
"X": "-..- ",
"Y": "-.-- ",
"Z": "--.. ",
"1": ".---- ",
"2": "..--- ",
"3": "...-- ",
"4": "....- ",
"5": "..... ",
"6": "-.... ",
"7": "--... ",
"8": "---.. ",
"9": "----. ",
"0": "----- ",
".": ".-.-.- ",
",": "--..-- ",
"?": "..--.. ",
"!": "..--. ",
"/": "-..-. ",
"#": ".--.-. ",
" ": " "
}
user_input = input("Input english or morse code message:\n").upper()
if all(c in translation for c in user_input):
morse = ''.join(map(translation.get, user_input))
print(morse)
elif all(c in ".- " for c in user_input):
print("*needs work in order to change morse to text*")
#trans_back = {v: k for k, v in translation.items()}
#text = ''.join(map(trans_back.get, user_input))
#print(text)
The difference between the two blocks is that the first block expects a character-by-character mapping, but the second block requires a block of characters to be mapped to a single key. You need to split user_input along the spaces so map will apply the function to a group of .s and -s representing a single key. Of course then you will also need to remove the spaces from your reversed dictionary lookup. Here's the code that I got to work:
elif all(c in ".- " for c in user_input):
trans_back = {v.rstrip(' '): k for k, v in translation.items()}
text = ''.join(map(trans_back.get, user_input.split(' ')))
print(text)
Related
This is the code below I want the output as: ("java developer" OR
"software developer") AND (angular) AND (core OR j2ee)
so AND has to be added for every output of for loop please help me-
x=input("Enter job title:").split()
y=input("enter primary skills:").split()
t=input("enter secondary skills").split()
for i in range(len(x)):
if len(x)==1:
print("("+ x[0]+")")
elif i==0:
["("+ x[i] +" OR "]
print("("+ x[i] +" OR ", end= " ")
elif i==(len(d)-1):
print(x[i] +")")
else:
print(x[i] + " OR ", end= " ")
for i in range(len(y)):
if len(y)==1:
print("("+ y[0]+")")
elif i==0:
print("("+ y[i] +" OR ", end= " ")
elif i==(len(y)-1):
print(y[i] +")")
else:
print(y[i] + " OR ", end= " ")
for i in range(len(t)):
if len(t)==1:
print("("+ t[0]+")")
elif i==0:
print("("+ t[i] +" OR ", end= " ")
elif i==(len(t)-1):
print(t[i] +")")
else:
print(t[i] + " OR ", end= " ")
i am getting output as
Execution:
Enter job title: javadeveloper software developer
enter primary skills: angular
enter secondary skills: core j2ee
(javadeveloper OR software OR developer)
(angular)
(core OR j2ee)
I want the output as: ("java developer" OR "software developer") AND (angular) AND (core OR j2ee)
check the following code:
from operator import indexOf
x = input("Enter job title:").replace(" developer","developer").split()
y=input("enter primary skills:").split()
t=input("enter secondary skills").split()
for i in range(len(x)):
varx = x[i]
if x[i].endswith("developer"):
varx = varx.replace("developer", " developer")
varx = '"' + varx +'"'
if len(x)==1:
print("("+ varx+")", end =" ")
elif i==0:
["("+ varx +" OR "]
print("("+ varx +" OR ", end= " ")
elif i==(len(x)-1):
print(varx +")", end =" ")
else:
print(varx + " OR ", end= " ")
print(" AND ", end =" ")
for i in range(len(y)):
if len(y)==1:
print("("+ y[0]+")", end =" ")
elif i==0:
print("("+ y[i] +" OR ", end= " ")
elif i==(len(y)-1):
print(y[i] +")", end =" ")
else:
print(y[i] + " OR ", end= " ")
print(" AND ", end =" ")
for i in range(len(t)):
if len(t)==1:
print("("+ t[0]+")", end =" ")
elif i==0:
print("("+ t[i] +" OR ", end= " ")
elif i==(len(t)-1):
print(t[i] +")", end =" ")
else:
print(t[i] + " OR ", end= " ")
What you've written is pretty confusing because of all the string manipulation. A better way to do this would be to first build a model of what you want, and then print it out.
The model could be a list of lists. Each item in the inner list should be 'OR'ed, and each item in the outer list should be 'AND'ed. So for your example, we would represent it as:
model = [
["java developer", "software developer"],
["angular"],
["core", "j2ee"],
]
Step 1: Generate the Model
It seems that terms can have multiple words, so splitting on whitespace is going to be ambiguous here. Instead we could split on something like ,.
We want to make everything as generic as possible, so here's a function that parses a string of comma separated terms into a list of terms. We can use this every time we want to take input from the user.
def parse_input_string(inp: str) -> list[str]:
return [s.strip() for s in inp.split(",")]
# e.g. parse_input_string("foo, bat bar") => ["foo", "bat bar"]
Step 2: Print the model
We can write a function that takes a row, and outputs an 'OR' statement. And then use that to write a function that gets the entire query statement.
def get_or_statement(items: list[str]) -> str:
# if there's a space in a term, wrap the term in quotes.
items = (f'"{item}"' if " " in item else item for item in items)
return f"({' OR '.join(items)})"
def get_query(model: list[list[str]]) -> str:
or_statements = [get_or_statement(items) for items in model]
return " AND ".join(or_statements)
print(get_query(model))
# ("java developer" OR "software developer") AND (angular) AND (core OR j2ee)
Step 3: Wrap it all together
Then our final program becomes quite simple:
model = [
parse_input_string(input("Enter job titles (comma separated): ")),
parse_input_string(input("Enter primary skills (comma separated): ")),
parse_input_string(input("Enter secondary skills (comma separated): ")),
]
print(get_query(model))
Output
Enter job titles (comma separated): java developer, software developer
Enter primary skills (comma separated): angular
Enter secondary skills (comma separated): core, j2ee
("java developer" OR "software developer") AND (angular) AND (core OR j2ee)
BREAK DOWN OF PROJECT
The user is asked to enter a number and a second number.
a variable named results is created by adding the two numbers
together.
We search for the results in the 1st if statement in a dictionary
named ans (short for answers).
This part functions as it should. It than gives those results back
to the user by displaying the original numerical equation. And a
version of the equation using letters (see full code below if you
are confused).
However if the results do not match the 1st if statement it moves to the next. Before the whole if statement a variable named search is created by:
search = tuple(str(results))
I need to now take the results and search each individual character and see if those characters also appear in the dictionary (ans). However, it's not searching for the tuple character strings in the dictionary.
FULL CODE
translate_results = {
1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H",
9: "I", 10: "J", 20: "T", 0: 0, "1": "A", "2": "B", "3": "C", "4": "D",
"5": "E", "6": "F", "7": "G", "8": "H", "9": "I", "0": "0",
}
ans = translate_results
user = input('Enter a number: ')
user2 = input('Enter another number: ')
results = int(user) + int(user2)
search = tuple(str(results))
if results in ans:
print(f"{user} + {user2} = {results}")
print(f"{ans[user]} + {ans[user2]} = {ans[results]}")
elif search in ans:
print(f"{user} + {user2} = {results}")
print(f"{ans[user]} + {ans[user2]} = {ans[search]}")
print(search)
else:
print(f" Answer is {results}")
print(f"However, elif statment failed. Tuple list created: {search}")
Example One
So if the user types in 1 (user) and 3 (user2) the output is:
1 + 2 = 3
A + B = C
Based on the 1st if statement.
Part 2 If Statement
This is suppose to activate when it finds the individual string characters from search (variable) in the dictionary (ans). Than it is suppose to take those characters match them in the dictionary and display the dictionary values instead.
Example Two (if it worked)
So the user enters 1 (user) and 29 (user2) the out put would be after matching variable search to ans:
1 + 29 = 30
A + BI = C0
something like this?
translate_results = {
1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H",
9: "I", 10: "J", 20: "T", 0: 0, "1": "A", "2": "B", "3": "C", "4": "D",
"5": "E", "6": "F", "7": "G", "8": "H", "9": "I", "0": "0",
}
ans = translate_results
user = input('Enter a number: ')
user2 = input('Enter another number: ')
results = int(user) + int(user2)
search = tuple(str(results))
if results in ans:
print(f"{user} + {user2} = {results}")
print(f"{ans[user]} + {ans[user2]} = {ans[results]}")
elif set(search).issubset(set(ans.keys())):
txt1= '' #for each create a string where the program appends the translated values
for i in user:
txt1+=str(ans[i])
txt2= ''
for i in user2:
txt2+=str(ans[i])
txtres= ''
for i in search:
txtres+=str(ans[i])
print(f"{user} + {user2} = {results}")
print(f"{txt1} + {txt2} = {txtres}")
print(search)
else:
print(f" Answer is {results}")
print(f"However, elif statment failed. Tuple list created: {search}")
inputs:
10, 15
output:
10 + 15 = 25
A0 + AE = BE
('2', '5')
also check the translate() function, if that can help.
This is a part of Morse code problem. I want to figure out how many words can be made from the encoded Morse code ensuring the word that is made would be of same length as input.
morseCode = {"A":".-","B":"-...","C":"-.-."}
morseCode["D"] = "-.."
morseCode["E"] = "."
morseCode["F"] = "..-."
morseCode["G"] = "--."
morseCode["H"] = "...."
morseCode["I"] = ".."
morseCode["J"] = ".---"
morseCode["K"] = "-.-"
morseCode["L"] = ".-.."
morseCode["M"] = "--"
morseCode["N"] = "-."
morseCode["O"] = "---"
morseCode["P"] = ".--."
morseCode["Q"] = "--.-"
morseCode["R"] = ".-."
morseCode["S"] = "..."
morseCode["T"] = "-"
morseCode["U"] = "..-"
morseCode["V"] = "...-"
morseCode["W"] = ".--"
morseCode["X"] = "-..-"
morseCode["Y"] = "-.--"
morseCode["Z"] = "--.."
#Retrieve end-user's message and convert it to upper case.
message = input("Type a message to convert in morse code (e.g. \"SOS\"?)").upper()
encodedMessage = ""
#Convert each letter into Morse code:
for character in message:
#Check that the character is in the Morse Code dictionary (e.g letter of the alphabet)
if character in morseCode:
encodedMessage += morseCode[character]
else:
#Replace unrecognised characters with a space
encodedMessage += ""
#Display the message in Morse code:
print("Your message in Morse code is:")
print(encodedMessage)
Input : eta
Your message in Morse Code is : .-.-
Output : 3
As 3 words of the same length as eta can be made with the encoded Morse code. (eta,ent,aet)
I'm not able to figure out how to find the number of words that can be made with the Morse code.
Something like this without optimizing:
morseCode = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"V": "...-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--.."
}
def countWords(msg, length, collected = ''):
if not msg:
if not length:
return [collected]
return []
current = []
for letter, code in morseCode.items():
if msg.startswith(code):
current.extend(countWords(msg[len(code):], length - 1, collected + letter))
return current
if __name__ == '__main__':
#Retrieve end-user's message and convert it to upper case.
message = input('Type a message to convert in morse code (e.g. "SOS"): ').upper()
encodedMessage = ""
#Convert each letter into morse code:
for character in message:
#Check that the character is in the moreCode dictionary (e.g letter of the alphabet)
if character in morseCode:
encodedMessage += morseCode[character]
else:
#Replace unrecognised characters with a space
encodedMessage += ""
#Display the message in morse code:
print("Your message in morse code is:", encodedMessage)
matches = countWords(encodedMessage, len(message))
print("There are", len(matches), "that match:")
for word in matches:
print(word)
and your example:
>py bla.py
Type a message to convert in morse code (e.g. "SOS"): ent
Your message in morse code is: .-.-
There are 3 that match:
AET
ENT
ETA
I keep getting an invalid sytnax error in the elif statement of my code. What am I doing wrong?
# define the functions for each math operation
#
def add (a, b) :
return a + b
def subtract (a, b) :
return a - b
def multiply (a, b) :
return a * b
def divide (a, b) :
return a / b
def remainder (a, b) :
return a % b
def welcome_message ( first_name ) :
print ("Hi ", first_name, " " ". Welcome to Project 3!")
welcome_message("Prof. Shah")
loop = 1
while loop ==1:
print ("Select operation.")
print ("1. Add")
print ("2. Subtract")
print ("3. Multiply")
print ("4. Divide")
print ("5. Remainder")
choice = input("Enter choice :")
num1 = int(input |"Please enter your first number: ")
num2 = int(input |"Please enter your second number: ")
if choice == '1' :
print(num1, "+", num2, "=", add (num1,num2)
elif choice == '2' :
print(num1, "-", num2, "=", subtract (num1,num2)
elif choice == '3' :
print(num1, "*", num2, "=", multiply (num1,num2)
elif choice == '4' :
print(num1, "/", num2, "=", divide (num1,num2)
elif choice == '5' :
print(num1, "%", num2, "=", remainder (num1,num2)
if choice == '1' :
print(num1, "+", num2, "=", add(num1,num2))
elif choice == '2' :
print(num1, "-", num2, "=", subtract(num1,num2))
...
your indentation seems to be off, and you were missing a closing brace at the end of every print statement.
if choice == '1' :
print(num1, "+", num2, "=", add (num1,num2)
elif choice == '2' :
print(num1, "-", num2, "=", subtract (num1,num2)
elif choice == '3' :
print(num1, "*", num2, "=", multiply (num1,num2)
elif choice == '4' :
print(num1, "/", num2, "=", divide (num1,num2)
elif choice == '5' :
print(num1, "%", num2, "=", remainder (num1,num2)
Problem is in here. if "if" block is going to process, then you have to start with if after then elif. like:
if choice == '1' :
print(num1, "+", num2, "=", add (num1,num2)
elif choice == '2' :
print(num1, "-", num2, "=", subtract (num1,num2)
elif choice == '3' :
print(num1, "*", num2, "=", multiply (num1,num2)
elif choice == '4' :
print(num1, "/", num2, "=", divide (num1,num2)
elif choice == '5' :
print(num1, "%", num2, "=", remainder (num1,num2)
I am a python newbie and I seem to be having an issue and I can't see what I am doing wrong. I am trying to make it so that when I enter a string it turns the string into pig latin. The issue is that when I do this it only prints out the first word in the string converted. Would anyone be able to point me in the right direction?
Cheers
def pig_latin(data):
words = data.split()
piglatin = []
vowels = ["a", "i", "e", "u", "o", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "0"]
for word in words:
if word[0] in vowels:
word = word + "way"
else:
word = word.replace(word[0],"") + word[0] + "ay"
word = word.lower()
piglatin.append(word)
piglatin = "".join(piglatin)
return piglatin
Check your indentation. Your return statement is inside the for loop, so it would return after the first iteration. You want to make sure the return is at the same indent level as the for statement.
def pig_latin(data):
words = data.split()
piglatin = []
vowels = ["a", "i", "e", "u", "o", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
for word in words:
if word[0] in vowels:
word = word + "way"
else:
word = word.replace(word[0],"") + word[0] + "ay"
word = word.lower()
piglatin.append(word)
piglatin = " ".join(piglatin)
return piglatin
Your return statement is inside the for loop due to bad indentation, so obviously it will return after one iteration.
Here is the code that will fix this, along with some other changes:
def pigetize(text, wovels):
return ((text + "way") if text[0] in wovels else (text[1:]+text[0]+"ay")).lower()
def pig_latin(data):
words = data.split()
piglatin = []
vowels = ["a", "i", "e", "u", "o"] + [str(x) for x in range(10)]
for word in words:
piglatin.append(pigetize(word, wovels))
return "".join(piglatin)