I wish to create a translator using Python 3 - python

I am looking to create a translator with Python that converts English into Morse Code. I was able to get it working but would like to improve it.
Here is what I have:
morse = {'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': '--..',
'0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..',
'9': '----.'}
print (morse['G'])
Now this works fine, but I would like for it to prompt me with a question such as "What would you like to translate?" and then have someone type (as a example) "This will will be converted to Morse Code". and have whatever is typed converted. Does anyone know a way to do this? it seems like such a hassle to type "print (morse['G'])" for each letter.

You can prompt users for input using the raw_input (python 2) or input (python 3) functions.
The input to these functions is the prompt that is displayed, and the function returns what is entered.
>stored_input = input('Please enter a line: ')
Please enter a line: Some input
>print stored_input
Some input
This function will return to you a string. I'll leave it up to you to learn how to break the string into its characters. Also, what if an input is not a capital letter or a number (e.g. a lower case number, or a '\')? Be sure to utilize google to figure out the rest, this question has been asked many, many times.

Related

How do I access something within a dictionary, thats within a list, thats within a dictionary?

How would I access the object 'c' in a print statement?
{'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
Overall code(API KEY REMOVED BUT ISNT THE ISSUE):
command = ""
while(command != "q"):
command = input("Choose [c] for current price, [p] for previous days price, and [q] to quit.")
if(command == "c"):
coin = input("Enter currency pair: ")
crypto_data = (requests.get(f'https://api.finage.co.uk/last/crypto/{coin}?apikey=API_KEY')).json()
print(f"The current price of {coin} is {crypto_data['price']}")
if(command == "p"):
coin = input("Enter currency pair: ")
crypto_data = (requests.get(f'https://api.finage.co.uk/agg/crypto/prev-close/{coin}?apikey=API_KEY')).json()
*print(f"The previous price of {coin} is {crypto_data['results']['c']}")*
being where I get the issue
I get back a variety of codes, mostly I cant call a string and it must be a slice or integer
I have tried a range statement as well but it also brings back an error
TIA!
The same way you would do it if they were in a dictionary first, then an array, and then a dictionary again:
crypto_data = {'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
print(crypto_data["results"][0]["c"])
This is because:
# crypto_data is a dictionary, so you can access items by their key, i.e.
crypto_data["results"]
# which returns an array: [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]
# so then access items in the array by their index, i.e.
crypto_data["results"][0]
# which returns a dictionary: {'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}
# so then access items in the dictionary by their key again, i.e.
crypto_data["results"][0]["c"]
# which returns an integer: 42364.13
if
myDict = {'symbol': 'BTCUSD', 'totalResults': 1, 'results': [{'o': 41002.26, 'h': 43361, 'l': 40875.51, 'c': 42364.13, 'v': 59454.94294, 't': 1647993599999}]}
then myDict["results"][0]["c"] would return 42364.1
It's because despite you know that the dictionary is within a list, you're trying to access the dictionary as if it wasn't within a list.
This is really important: this API can return more than one dictionary in the results list - see the totalResults key.
The best way to get the results is to do a for ... range loop:
for idx in range(crypto_data['totalResults']): print(crypto_data['results'][idx])

Python 3.6 for loop is only printing one string per line, why? [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 5 years ago.
I am making a small Morse Code translator, and everything works fine; nonetheless, the output is not shown properly.
CIPHER = {'E': "⦾", "A": '⦿', 'R': '⦾⦿', 'I': '⦿⦾', 'O': '⦿⦿',
'T': '⦾⦾⦿', 'N': '⦾⦿⦾', 'S': '⦾⦿⦿', 'L': '⦿⦾⦾',
'C': '⦿⦾⦿', 'U': '⦿⦿⦾', 'D': '⦿⦿⦿',
'P': '⦾⦾⦾⦿', 'M': '⦾⦾⦿⦾', 'H': '⦾⦾⦿⦿',
'G': '⦾⦿⦾⦾', 'B': '⦾⦿⦾⦿', 'F': '⦾⦿⦿⦾',
'Y': '⦾⦿⦿⦿', 'W': '⦿⦾⦾⦾', 'K': '⦿⦾⦾⦿',
'V': '⦿⦾⦿⦾', 'X': '⦿⦾⦿⦿', 'Z': '⦿⦿⦾⦾',
'J': '⦿⦿⦾⦿', 'Q': '⦿⦿⦿⦾',
'1': '⦾⦾⦾⦾⦿', '2': '⦾⦾⦾⦿⦿', '3': '⦾⦾⦿⦿⦿',
'4': '⦾⦿⦿⦿⦿', '5': '⦿⦿⦿⦿⦿', '6': '⦿⦾⦾⦾⦾',
'7': '⦿⦿⦾⦾⦾', '8': '⦿⦿⦿⦾⦾', '9': '⦿⦿⦿⦿⦾',
'0': '⦿⦿⦿⦿⦿'
}
def main():
msg = input("Type your message below:\n\n")
for char in msg:
if char == ' ':
print (' '*7,)
elif char not in 'abcdefghijklmnopqrstuvwxyz1234567890':
print ('')
else:
print (CIPHER[char.upper()])
I would expect the output for "Hello, World!" to be something like this:
⦾⦿⦾⦾⦿⦾⦾⦿⦿ ⦿⦿⦾⦿⦿⦾⦾⦿⦿⦿
However, the actual output looks much more like this:
⦾
⦿⦾⦾
⦿⦾⦾
⦿⦿
⦿⦿
⦾⦿
⦿⦾⦾
⦿⦿⦿
I tried removing and placing commas randomly. Then, I tried removing the '\n' statements on the input, but nothing changed with respect to the output. I tried to use the .splitlines as shown here (For loop outputting one character per line), but it stopped printing completely! Then, I googled it and did not found anything close to this problem, so I started to read more material on Python strings. I found a website (https://automatetheboringstuff.com/chapter6/) that has a good amount of material about Python strings, but I could not find anything that could solve my problem there.
I would greatly appreciate your help!
You seem to be accustomed to Python2 convention of using comma at the end of print arguments to prevent automatically adding newline. This is no longer working in Python3. You should use keyword argument end='' instead, like this: print (' '*7, end='')
Use
print(sth, end='')
to print without breaking line.

Turning an integer string to an integer in Python

I am trying to write a program in python that codes items by first turning the input word to Morse and then changes the dots and dashes to ones and zeros which will be treated as binary numbers etc.
This is a code snippet:
def mimary_encode(input):
if input.find('!')!=-1 or input.find('#')!=-1 or input.find('#')!=-1 or input.find('$')!=-1 or input.find('%')!=-1 or input.find('^')!=-1 or input.find('&')!=-1 or input.find('*')!=-1 or input.find('(')!=-1 or input.find(')')!=-1 or input.find('_')!=-1 or input.find('-')!=-1 or input.find('=')!=-1 or input.find('+')!=-1 or input.find('.')!=-1 or input.find('"')!=-1 or input.find("'")!=-1 or input.find(',')!=-1 or input.find(' ')!=-1 or input.find(';')!=-1 or input.find(':')!=-1 or input.find('[')!=-1 or input.find(']')!=-1 or input.find('{')!=-1 or input.find('}')!=-1 or input.find('?')!=-1 or input.find('<')!=-1 or input.find('>')!=-1:
print "Inputs cannot contain spaces or symbols"
else:base=input
nol=len(input)
if base.find("a")!=-1:
base=base.replace("a",".-")
if base.find("b")!=-1:
base=base.replace("a","-...")
if base.find("c")!=-1:
base=base.replace("c","-.-.")
if base.find("d")!=-1:
base=base.replace("d","-..")
if base.find("e")!=-1:
base=base.replace("e",".")
if base.find("f")!=-1:
base=base.replace("f","..-.")
if base.find("g")!=-1:
base=base.replace("g","--.")
if base.find("h")!=-1:
base=base.replace("h","....")
if base.find("i")!=-1:
base=base.replace("i","..")
if base.find("j")!=-1:
base=base.replace("j",".---")
if base.find("k")!=-1:
base=base.replace("k","-.-")
if base.find("l")!=-1:
base=base.replace("l",".-..")
if base.find("m")!=-1:
base=base.replace("m","--")
if base.find("n")!=-1:
base=base.replace("n","-.")
if base.find("o")!=-1:
base=base.replace("o","---")
if base.find("p")!=-1:
base=base.replace("p",".--.")
if base.find("q")!=-1:
base=base.replace("q","--.-")
if base.find("r")!=-1:
base=base.replace("r",".-.")
if base.find("s")!=-1:
base=base.replace("s","...")
if base.find("t")!=-1:
base=base.replace("t","-")
if base.find("u")!=-1:
base=base.replace("u","..-")
if base.find("v")!=-1:
base=base.replace("v","...-")
if base.find("w")!=-1:
base=base.replace("w",".--")
if base.find("x")!=-1:
base=base.replace("x","-..-")
if base.find("y")!=-1:
base=base.replace("y","-.--")
if base.find("z")!=-1:
base=base.replace("z","--..")
if base.find("1")!=-1:
base=base.replace("1",".----")
if base.find("2")!=-1:
base=base.replace("2","..---")
if base.find("3")!=-1:
base=base.replace("3","...--")
if base.find("4")!=-1:
base=base.replace("4","....-")
if base.find("5")!=-1:
base=base.replace("5",".....")
if base.find("6")!=-1:
base=base.replace("6","-....")
if base.find("7")!=-1:
base=base.replace("7","--...")
if base.find("8")!=-1:
base=base.replace("8","---..")
if base.find("9")!=-1:
base=base.replace("9","----.")
if base.find("0")!=-1:
base=base.replace("0","-----")
if base.find("-")!=-1:
base=base.replace("-","0")
if base.find(".")!=-1:
base=base.replace(".","1")
int(base)
mimary_encode("hi")
I know this is probably not the best way to write it, but the problem is the error python keeps giving me is:
Traceback (most recent call last):
File "C:/Documents and Settings/Moshe's Programming/Desktop/Python
Projects/Mimary/Mimary attempt 1.py", line 86, in <module>
mimary_encode("hi")
File "C:/Documents and Settings/Moshe's Programming/Desktop/Python
Projects/Mimary/Mimary attempt 1.py", line 83, in mimary_encode
print base + 1
TypeError: cannot concatenate 'str' and 'int' objects
What does this error mean? How can I fix this error? I already did turn base into an integer-didn't I?
Although your code is reaaally messed up, it works. However, your first error was raised due to the line int("base").
If you write int("base") you are trying to turn the string "base" into an integer, which is something impossible to do.
Then, you changed the code to print base + 1 which is also impossible to do, once base is a string and you can't sum strings and integers with + sign.
So, what you want to do is:
def mimary_encode(base):
#Dowhateveryouwant
return int(base) #Only if you are sure base contains only integers
print mimary_encode("hi")
The error is coming from print base + 1, where base is a string and 1 an integer.
Here is an alternative implementation of your function. First, I define the morse code encoding as a dictionary. In the function, I first convert all letters to lower case. I then use the get dictionary function to return the morse code value if it is in the dictionary, otherwise it uses an empty string to filter it. This differs from the original approach where bad data is filtered. Here, I'm only looking for data that is in my dictionary. Finally, I join together the encoded letters using a generator: code = " ".join((morse.get(c, "") for c in input_string)) which is similar to list comprehension but more efficient for large strings.
from string import letters
msg = 'I hear 13 knights from the Round Table are here!!!'
def mimary_encode(input_string):
input_string = ''.join([c.lower() if c in letters else c
for c in input_string])
code = " ".join((morse.get(c, "") for c in input_string))
return code
morse = {
'0': '-----',
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
'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': '--..'}
To encode the message (defined earlier as msg):
>>> mimary_encode(msg)
'.. .... . .- .-. .---- ...-- -.- -. .. --. .... - ... ..-. .-. --- -- - .... . .-. --- ..- -. -.. - .- -... .-.. . .- .-. . .... . .-. .'
Given the one-to-one mapping of your dictionary, you can reverse it using a dictionary comprehension:
reverse_morse = {v: k for k, v in morse.iteritems()}
You can then reverse the morse code to convert it back into an alpha/numeric string.
>>> ''.join([reverse_morse.get(c, "") for c in mimary_encode(msg).split(" ")])
'ihear13knightsfromtheroundtablearehere'
Notice that all letters are converted to lower case and that the exclamations have been removed.

hexToBinary dictionary

So I am working on this problem: Recall from the Number Systems unit the method for converting hexadecimal numbers to
binary by converting each hex digit to its equivalent four binary digits. Write a Python
function named hexToBinary with parameters (number, table) that uses this algorithm to
convert a hexadecimal number to a (return) binary number. The algorithm visits each digit
in the hexadecimal number, selecting from table the corresponding four bits that represent
that digit in binary and then adds these bits to the result string.
This is the code I have written, but I'm not getting it able to work properly:
def hexToBinary (hex, table):
hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
final_hexToBinary = ''
for hex in hexToBinary:
final_hexToBinary+=hex
print(final_hexToBinary)
I am wondering what is wrong with the function, I have a feeling it is a simple mistake.
You forget this:
final_hexToBinary += hexToBinary[hex]
Also:
'table' -- not used var.
hexToBinary name of function and dict.
hex -- reserved word, argument and iterator.
It's not a problem, but sometime you can achieve mistake with that.
def hexToBinary (hex, table):
final_hexToBinary = ''
for each in hex:
final_hexToBinary+=table[each]
print(final_hexToBinary)
hexToBinaryTable = {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
hexToBinary("3FB",hexToBinaryTable)
As mentioned it comment your might want to look up the dictionary.
If you need not implement the function go for the one mentioned by john galt in comment.
if I am correct you are trying this:
def hexToBinary(my_hex):
hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
final_hexToBinary = ''
for x in my_hex: # here it should be my_hex instead of table
final_hexToBinary += hexToBinary[x] # here was the mistake
print(final_hexToBinary)
hexToBinary("ABC12")
output:
10101011110000010010
NOTE: dont use hex as variable name its built-in python
Try this:
hexToBinary= {'0':'0000', '1':'0001', '2':'0010','3':'0011', '4': '0100', '5': '0101', '6':'0110', '7': '0111', '8': '1000', '9': '1001', 'A': '1010', 'B': '1011', 'C': '1100', 'D': '1101', 'E': '1110', 'F': '1111'}
to_conv= input("enter a num: ")
final_hexToBinary = ''
for hex in to_conv:
final_hexToBinary += hexToBinary.get(hex,"!!") + " "
print(final_hexToBinary)

Translating characters in a string to multiple characters using Python

I have a list of strings with prefix characters representing the multiplying factor for the number. So if I have data like:
data = ['101n', '100m', '100.100f']
I want to use the dictionary
prefix_dict = {'y': 'e-24', 'z': 'e-21', 'a': 'e-18', 'f': 'e-15', 'p': 'e-12',
'n': 'e-9', 'u': 'e-6', 'm': 'e-3', 'c': 'e-2', 'd': 'e-1',
'da': 'e1', 'h': 'e2', 'k': 'e3', 'M': 'e6', 'G': 'e9',
'T': 'e12', 'P': 'e15', 'E': 'e18', 'Z': 'e21', 'Y': 'e24'}
To insert their corresponding strings. When I look at the other questions similar to mine there is one character being translated into another character. Is there a way to use the translate function to translate one character into multiple characters or should I be approaching this differently?
You can use regex for this, this works for 'da' as well:
>>> data = ['101n', '100m', '100.100f', '1d', '1da']
>>> import re
>>> r = re.compile(r'([a-zA-Z]+)$')
>>> for d in data:
print r.sub(lambda m: prefix_dict.get(m.group(1), m.group(1)), d)
...
101e-9
100e-3
100.100e-15
1e-1
1e1
And a non-regex version using itertools.takewhile:
>>> from itertools import takewhile
>>> def find_suffix(s):
return ''.join(takewhile(str.isalpha, s[::-1]))[::-1]
...
>>> for d in data:
sfx = find_suffix(d)
print (d.replace(sfx, prefix_dict.get(sfx, sfx)))
...
101e-9
100e-3
100.100e-15
1e-1
1e1
Try:
for i, entry in enumerate(data):
for key, value in sorted(prefix_dict.items(),
key = lambda x: len(x[0]), reverse=True):
# need to sort the dictionary so that 'da' always comes before 'a'
if key in entry:
data[i] = entry.replace(key, value)
print(data)
This works for arbitrary combinations in the dictionary and the data. If the dictionary key is always only 1 string long, you have lots of other solutions posted here.
import re
data = ['101da', '100m', '100.100f']
prefix_dict = {'y': 'e-24', 'z': 'e-21', 'a': 'e-18', 'f': 'e-15', 'p': 'e-12',
'n': 'e-9', 'u': 'e-6', 'm': 'e-3', 'c': 'e-2', 'd': 'e-1',
'da': 'e1', 'h': 'e2', 'k': 'e3', 'M': 'e6', 'G': 'e9',
'T': 'e12', 'P': 'e15', 'E': 'e18', 'Z': 'e21', 'Y': 'e24'}
comp = re.compile(r"[^\[A-Za-z]")
for ind,d in enumerate(data):
pre = re.sub(comp,"",d)
data[ind] = d.replace(pre,prefix_dict.get(pre))
print data
['101e1', '100e-3', '100.100e-15']
You can use pre = [x for x in d if x.isalpha()][0] instead of using re

Categories