Turning an integer string to an integer in Python - 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.

Related

Don't undestand cause of this 'dict' object is not callable" error

I am trying to write a program that asks the user to enter a sentence, then it counts and displays the occurrence of each letter.
I have to write a program using loops and collections/containers, which counts all the letters in a sentence input and displays how many times each was used. 'A' and 'a' count as the same letter.
This is my code so far:
def split(sentence):
return [char for char in sentence]
def get_key(val):
for key, value in letters.items():
if val == value:
return key
letters = {'a': ['a','A'], 'b': ['b','B'], 'c': ['c','C'], 'd': ['d','D'], 'e': ['e','E'], 'f': ['f','F'], 'g': ['g','G'],
'h': ['h','H'], 'i': ['i','I'],'j': ['j','J'], 'k': ['k','K'], 'l': ['l','L'], 'm': ['m','M'], 'n': ['n','N'], 'o': ['o','O'],
'p': ['p','P'], 'q': ['q','Q'], 'r': ['r','R'], 's': ['s','S'], 't': ['t','T'], 'u': ['u','U'], 'v': ['v','V'], 'w': ['w','W'],
'x': ['x','X'], 'y': ['y','Y'], 'z': ['z','Z']}
sentence = str(input("Enter a sentence: "))
sentence_letters = split(sentence)
i = 0
while i in range(len(sentence_letters)):
actual_letter = sentence_letters[i]
for key,value in letters():
if value == actual_letter:
print(actual_letter + ':' + str(sentence_letters.count(actual_letter)) + 'times')
sentence_letters.remove(actual_letter)
i += 1
else:
i += 1
This is the most recent message I get when I run the code:
Traceback (most recent call last):
File "main.py", line 21, in <module>
for key,value in letters():
TypeError: 'dict' object is not callable
I do not know what I am doing wrong, I am not even sure if this is the right way to solve this.
Note that there are other ideas that would be helpful here, just focusing on your error:
Looking at letters() - following an identifier by parentheses like this attempts to call it as you would a function. Because letters is not a function (or anything else that can be called) it can't be called. This is what the error is telling you.

Python: Automatically introduce slight word-typos into phrases?

Has anyone ideas on how to automatically introduce common typos into words of a phrase?
I found this one How to introduce typo in a string? but I think it's a bit too generic because it simply replaces every n-th letter by a random character.
I would like to kind of introduce "common" typos.
Any idea on how to do it?
For the purpose of my explanation, let's assume that you have a String variable messages that you would like to introduce typos into. My strategy for introducing typos to messages that are both typos and common, would be to replace random letters in messages with other letters that are nearby on the keyboard (ie replace a with s or d with f). Here's how:
import random # random typos
message = "The quick brown fox jumped over the big red dog."
# convert the message to a list of characters
message = list(message)
typo_prob = 0.1 # percent (out of 1.0) of characters to become typos
# the number of characters that will be typos
n_chars_to_flip = round(len(message) * typo_prob)
# is a letter capitalized?
capitalization = [False] * len(message)
# make all characters lowercase & record uppercase
for i in range(len(message)):
capitalization[i] = message[i].isupper()
message[i] = message[i].lower()
# list of characters that will be flipped
pos_to_flip = []
for i in range(n_chars_to_flip):
pos_to_flip.append(random.randint(0, len(message) - 1))
# dictionary... for each letter list of letters
# nearby on the keyboard
nearbykeys = {
'a': ['q','w','s','x','z'],
'b': ['v','g','h','n'],
'c': ['x','d','f','v'],
'd': ['s','e','r','f','c','x'],
'e': ['w','s','d','r'],
'f': ['d','r','t','g','v','c'],
'g': ['f','t','y','h','b','v'],
'h': ['g','y','u','j','n','b'],
'i': ['u','j','k','o'],
'j': ['h','u','i','k','n','m'],
'k': ['j','i','o','l','m'],
'l': ['k','o','p'],
'm': ['n','j','k','l'],
'n': ['b','h','j','m'],
'o': ['i','k','l','p'],
'p': ['o','l'],
'q': ['w','a','s'],
'r': ['e','d','f','t'],
's': ['w','e','d','x','z','a'],
't': ['r','f','g','y'],
'u': ['y','h','j','i'],
'v': ['c','f','g','v','b'],
'w': ['q','a','s','e'],
'x': ['z','s','d','c'],
'y': ['t','g','h','u'],
'z': ['a','s','x'],
' ': ['c','v','b','n','m']
}
# insert typos
for pos in pos_to_flip:
# try-except in case of special characters
try:
typo_arrays = nearbykeys[message[pos]]
message[pos] = random.choice(typo_arrays)
except:
break
# reinsert capitalization
for i in range(len(message)):
if (capitalization[i]):
message[i] = message[i].upper()
# recombine the message into a string
message = ''.join(message)
# show the message in the console
print(message)

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.

How to write String template file with multiple loop elements?

I have small issue in writing for loop elements in string template as follows: when I try to make a string templete from three loop elements I can able to print only the last element not the first two elements. I beleive that the error is because of some issues in writing file but I couldnt get what is the actual problem is with my code. So If some one could you kindly help me with this.
My SCRIPT:
from string import Template
import os
AMONIOACIDS = {'A': 'ALA', 'C': 'CYS', 'E': 'GLU', 'D': 'ASP', 'G': 'GLY',
'F': 'PHE', 'I': 'ILE', 'H': 'HIS', 'K': 'LYS', 'M': 'MET',
'L': 'LEU', 'N': 'ASN', 'Q': 'GLN', 'P': 'PRO', 'S': 'SER',
'R': 'ARG', 'T': 'THR', 'W': 'TRP', 'V': 'VAL', 'Y': 'TYR'}
rPrS={'C': '102', 'A': '104','H': '12'}
a=[]
b=[]
count=1
for single, third in AMONIOACIDS.iteritems():
for rS,rP in rPrS.iteritems():
if rS == single:
a.append(["s"+str(count)+"=selection(mdl1.chains["+chain+"].residues["+rP+"])"])
b.append(["s"+str(count)+".mutate(residue_type='"+third+"')"])
str='''Loop elements\n'''
for i,j in zip (a,b):
i=''.join(i)
j=''.join(j)
str+='''$i\n'''
str+='''$j\n'''
str=Template(str)
str.substitute(i=i, j=j)
file = open(os.getcwd() + '/' + 'model.py', 'w')
file.write(str.substitute(i=i,j=j))
file.close()
Expected ouput:
Loop elements
s1=selection(mdl1.chains[A].residues[104])
s1.mutate(residue_type='ALA')
s2=selection(mdl1.chains[A].residues[102])
s2.mutate(residue_type='CYS')
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')
What I am getting :
Loop elements
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')
s3=selection(mdl1.chains[A].residues[12])
s3.mutate(residue_type='HIS')
Your template is getting its substitution values from the last values of i and j from the for loop. You need to persist values from the previous iteration. How? You could use a dictionary and a count to store and distinguish values at each iteration.
You can substitute values in a template using a dictionary. I have used the count variable to create corresponding dictionary keys at each iteration: i_0, i_1, i_2, and j_0, j_1, j_2. These same names are used as identifiers in the template $i_0, $i_1, $i_2, and $j_0, $j_1, $j_2.
safe_substitute safely substitutes the value at each key into the template e.g key i_0 to the template identifier $i_0.
The dictionary stores all values of i and j at each iteration, and the substitution in your template is done taking the appropriate values at each key in the dictionary. This part should fix it:
# your previous lines of code
count = 0
d = {}
s='''Loop elements\n'''
for i,j in zip (a,b):
d['i_{}'.format(count)] = ''.join(i)
d['j_{}'.format(count)] = ''.join(j)
s+='$i_{}\n'.format(count)
s+='$j_{}\n'.format(count)
count += 1
print(str)
print(d)
s=Template(s)
file = open(os.getcwd() + '/' + 'model.py', 'w')
file.write(s.safe_substitute(d))
file.close()
I have replaced the name str with s to avoid shadowing the builtin str. No other changes are required in the preceding code blocks before the fix.

I wish to create a translator using Python 3

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.

Categories