I am having trouble finishing this code. My original plan was to accept a long string as input , for example '... ---.. -. -.. .... . .-.. .--.' and then be able to use morse_code = [code_input.split(' ')] to separate them and run them individually but I am either getting the first character returning from the index or no return at all so can anyone help me mend this or help lead me in the way of a simpler solution?
Thanks to all for any help!
#morse code converter
def main():
code_input = get_input()
morse_code(code_input)
def get_input():
return input('Enter morse code: ')
def morse_code(code_input):
morse_code = [code_input]
convert = ['--..--', '.-.-.-', '..--..', '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..',
'----.', '.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---' ,'-.-', '.-..', '--', '-.', '---',
'.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.-', '--..']
new = [',', '.', '?', '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',]
print(morse_code)
length = len(morse_code)
for x in range(length):
for value in range(39):
if morse_code[x] == convert[value]:
print(new[value])
main()
Your idea to use split should work just fine:
>>> '... ---.. -. -.. .... . .-.. .--.'.split()
['...', '---..', '-.', '-..', '....', '.', '.-..', '.--.']
For the translation, I would use a dictionary instead of a list:
morse2text = {'...': 's', '---': 'o'}
To avoid key errors, I would a do a "safe lookup" using the dictionary get() method:
print( morse2text.get(m, m) )
Here is all the code put together (though with an incomplete dictionary) in case you want to build-off of a working example:
morse2text = {
'.-': 'a',
'-..': 'd',
'.': 'e',
'....': 'h',
'..': 'i',
'-.': 'n',
'---': 'o',
'...': 's',
'-': 't',
}
s = '... ---.. -. -.. .... . .-.. .--.'
for m in s.split():
print( morse2text.get(m, m) )
This should work for you:
def morse_code(code_input):
morse_codes = code_input.split(' ')
convert = ['--..--', '.-.-.-', '..--..', '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..',
'----.', '.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---' ,'-.-', '.-..', '--', '-.', '---',
'.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.-', '--..']
new = [',', '.', '?', '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',]
print(morse_codes)
code = ''
for x in morse_codes:
index = convert.index(x)
code+=new[index]
return code
print morse_code('... ---.. -. -.. .... . .-.. .--.')
Output:
['...', '---..', '-.', '-..', '....', '.', '.-..', '.--.']
'S8NDHELP'
As the Legendary Raymond mentioned, dict type is a better option.
Try dict(zip(convert,new)) to make a dictionary for conversion.
d = {'--..--': ',', '....-': '4', '.....': '5', '-...': 'B', '-..-': 'X',
'.-.': 'R', '--.-': 'Q', '--..': 'Z', '.--': 'W', '..---': '2',
'.-': 'A', '..': 'I', '-.-.': 'C', '...--': '3', '-': 'T', '.': 'E',
'.-..': 'L', '...': 'S', '..-': 'U', '..--..': '?', '.----': '1',
'.--.': 'P', '-----': '0', '-.-': 'Y', '-..': 'D', '----.': '9',
'-....': '6', '.---': 'J', '---': 'O', '.-.-.-': '.', '--': 'M',
'-.': 'N', '....': 'H', '---..': '8', '...-': 'V', '--...': '7',
'--.': 'G', '..-.': 'F'}
To use the dict:
translation = ''
for c in morse_codes:
translation += d[c]
Related
Is there a "base64.b85decode" function in nodejs?
It uses the following character set -
0123456789
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
!#$%&()*+-;<=>?#^_`{|}~
It's not a regular Ascii85 encoding but a different base85 encoding type.
For example, for "Hello, world!!!!", It should return "NM&qnZ!92pZpv8At50l"
I solved it by using the ascii85 package and using a customized character set -
var ascii85 = require('ascii85');
ascii85.decode(to_decode, ['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', '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', '!', '#', '$', '%', '&', '(', ')', '*', '+', '-', ';', '<', '=', '>', '?', '#', '^', '_', '`', '{', '|', '}', '~']).toString('ascii');
def main():
list_one = ['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']
list_two = ['4', 'R', '5', 'G', 'Z', '3', '2', 'D', 'A', 'E', 'X', 'Y', 'U', 'I', '6', 'W', '7', 'O', 'V', '8', 'F', 'Q', 'L', '0', 'J', '.', 'H', '9', 'C', 'B', 'N', 'S', 'P', 'M', '1', 'T', 'K']
code = str(input("Enter message here. ")).upper()
question = str(input("Would you like to encrypt or decrypt? ")).lower()
if question == "encrypt":
code_encrypt(list_one, list_two, code)
#elif question == "decrypt":
else:
print("Invalid Input, Try Again")
main()
def code_encrypt(x, y, z):
message = ''
for i in (z):
for j in range(len(x)):
if i == x[j]:
message = message + repr(y[j])
print(str.strip(message))
main()
output is
Enter message here. yusef
Would you like to encrypt or decrypt? encrypt
'J''F''V''Z''3'
problem is^^^ i cant have those '''' around the output. it needs to be JFVZ3
Just remove "representation" conversion repr():
def code_encrypt(x, y, z):
message = ''
for i in (z):
for j in range(len(x)):
if i == x[j]:
message = message + y[j]
print(message)
I am very new to Python and have only just bought my first "Crashcourse in Python" book - originally my choice of language was PHP.
My Objective:
I desire a script that will output on-screen a list of all possible permutations of a particular pattern. Order is unimportant.
The raw data and pattern (the dataset will not change):
List1 = ['CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY']
List2 = ['51', '02', '52', '03', '53', '04', '54', '05', '55', '06', '56', '07', '57', '08', '58', '09', '59', '10', '60', '11', '61', '12', '62', '13', '63', '14', '64', '15', '65', '16', '66', '17']
List3 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
List4 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
List5 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
String Output:
[List1] + [List2] + [List3] + [List4] + [List5]
Example:
Resulting in lots of 7 character alphanumeric strings
CH07YCD
CT11MPP
etc.
Crap Maths:
Is my wonky maths correct in that I'd be looking at 10,174,464 entries? List1(23) x List2(32) x List3,4,5(13,824).
My question:
Is itertools the best function to use for this? If so, how? If not, what?
>>> import itertools
>>> s = [List1, List2, List3, List4, List5]
>>> n = list(itertools.product(*s))
>>> len(n)
10174464
itertools.product -> Roughly equivalent to nested for-loops in a generator expression.
I have a problem for school and I can't seem to figure it out. Basically, i'm in an intro to object oriented programming class, so I only need to complete this as basic as possible without using anything fancy that I haven't learned yet. Currently learning about dictionaries and sets, I need to use a dictionary that has a code written in it to encrypt a document that has a long string on one line.
So I need one part to read the dictionary and open the text file containing the string.
"The course Introduction to Object Oriented Programming uses the Python programming language."
I need to then use the code from this dictionary to encrypt it and write the encrypted version of the string to another text file called encrypt.txt.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
This is the code I have so far. Any help would be greatly appreciated and an explanation in layman's terms would also be greatly appreciated.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
def main():
#Open the file you want to encrypt.
infile = str(input('Enter the name of the input file: '))
#read its contents
dtext = open(infile, 'r')
#read the line from the file
dtext = dtext.readlines()
#strip the newline
#dtext = dtext.rstrip('\n')
#call the encryptText function
encryptText(dtext)
def encryptText(dtext):
#enter the name of the file to write to
outfile = str(input('Enter the name of the output file: '))
#open the file to send encrypted text to
etext = open(outfile, 'w')
#set accumulator value
count = 0
#create a for loop to read each separate character
for line in dtext:
wordList = line.split()
print(dtext, CODE[dtext])
count += 1
main()
You need to encrypt character by character and you need to take the result and build it back into a string. str.join turns a sequence of characters into a string and a generator can be written to encrypt each character... put them together and you have your solution.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
def main():
#Open the file you want to encrypt.
infile = str(input('Enter the name of the input file: '))
#read its contents
dtext = open(infile, 'r')
#read the line from the file
dtext = dtext.readlines()
#strip the newline
#dtext = dtext.rstrip('\n')
#call the encryptText function
encryptText(dtext)
def encryptText(dtext):
#enter the name of the file to write to
outfile = str(input('Enter the name of the output file: '))
#open the file to send encrypted text to
etext = open(outfile, 'w')
#set accumulator value
#create a for loop to read each separate character
for line in dtext:
# encrypt character by character then join to a string
encrypted = ''.join(CODE.get(c, c) for c in line)
print(repr(line), repr(encrypted))
etext.write(encrypted)
etext.close()
main()
Strings are immutable. That means you cannot edit them after creation, in direct contrast to arrays. You will have to build a new string in order to encrypt your text. You will also likely need to do this one character at a time. Since you have the text of the file in dtext as a string, you can loop through the chars in the original string like so:
for i in range (0, len(dtext)):
# add new character to string
(I'm breaking this apart so you cannot just copy and paste)
You must create a new string to put the encrypted text in outside of that for loop.
enc = ""
In order to encrypt the value by making a substitution you can add character one at a time to the encrypted string in that for loop if they are in the dictionary you defined. Something to the effect of
if (dtext[i] in CODE.keys()):
enc += CODE[dtext[i]]
Then write the new string to a file and you're good to go.
A dictionary in python is effectively an array that is indexable by a key. This key maps to a given value just like an array index maps to some value. See https://www.tutorialspoint.com/python/python_dictionary.htm for more details.
tdelaney's answer was correct, but I took it and made it a more simpler version. I changed it a bit. This is what I did:
Instead of joining to an empty string, I just removed that part completely. I just iterated over the entire string character by character and then as tdelaney did, used the get method to use the key in the code dictionary.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
def main():
#Open the file you want to encrypt.
infile = str(input('Enter the name of the input file: '))
#read its contents
dtext = open(infile, 'r')
#read the line from the file
dtext = dtext.readlines()
#call the encryptText function
encryptText(dtext)
def encryptText(dtext):
#enter the name of the file to write to
outfile = str(input('Enter the name of the output file: '))
#open the file to send encrypted text to
etext = open(outfile, 'w')
#create a for loop to read each separate character
for line in dtext:
# encrypt character by character then join to a string
for c in line:
encrypted = (CODE.get(c, c))
etext.write(encrypted)
#close the file
etext.close()
main()
I have two, unequal length lists. The first list contains variable names for a longitudinal study, the other contains suffixes for these variables. The user supplies a CSV from which the variable names are read, and then is prompted to enter the (n) number of iterations of these variables, and the names of the n number of suffixes
Here is a fake example of what I mean
Number of iterations: 2
Suffix1: pre
Suffix2: 6month
List 1:
['mood1', 'mood2', 'mood3', 'dep1', 'dep2', 'dep3']
List 2:
['pre', '6month']
Desired concatenation:
['mood1_pre', 'mood2_pre', 'mood3_pre', 'dep1_pre', 'dep2_pre', 'dep3_pre', 'mood1_6month', ..., 'dep3_6month']
I have the program working fully, except the output splits each letter of the concatenated list into its own element, for example:
How many iterations of the variables do you need?: 3
Variable Suffix 1: pre
Variable Suffix 2: 6m
Variable Suffix 3: 12m
['B', 'o', 'b', '_', 'p', 'r', 'e', 'J', 'o', 'e', '_', 'p', 'r', 'e', 'J', 'i',
'm', '_', 'p', 'r', 'e', 'A', '_', 'p', 'r', 'e', 'B', '_', 'p', 'r', 'e', 'C',
'_', 'p', 'r', 'e', '1', '_', 'p', 'r', 'e', '2', '_', 'p', 'r', 'e', '3', '_',
'p', 'r', 'e', '1', '4', '_', 'p', 'r', 'e', 'B', 'o', 'b', '_', '6', 'm', 'J',
'o', 'e', '_', '6', 'm', 'J', 'i', 'm', '_', '6', 'm', 'A', '_', '6', 'm', 'B',
'_', '6', 'm', 'C', '_', '6', 'm', '1', '_', '6', 'm', '2', '_', '6', 'm', '3',
'_', '6', 'm', '1', '4', '_', '6', 'm', 'B', 'o', 'b', '_', '1', '2', 'm', 'J',
'o', 'e', '_', '1', '2', 'm', 'J', 'i', 'm', '_', '1', '2', 'm', 'A', '_', '1',
'2', 'm', 'B', '_', '1', '2', 'm', 'C', '_', '1', '2', 'm', '1', '_', '1', '2',
'm', '2', '_', '1', '2', 'm', '3', '_', '1', '2', 'm', '1', '4', '_', '1', '2',
'm']
I am using this to make the new list
newvarlist.extend((varlist[vars] + '_' + varsuffix[j]))
Here is one way to do it using list comprehension:
['{}_{}'.format(a, b) for b in b_list for a in a_list]
Demo:
>>> a_list = ['mood1', 'mood2', 'mood3', 'dep1', 'dep2', 'dep3']
>>> b_list = ['pre', '6month']
>>> result = ['{}_{}'.format(a, b) for b in b_list for a in a_list]
>>> result
['mood1_pre', 'mood2_pre', 'mood3_pre', 'dep1_pre', 'dep2_pre', 'dep3_pre', 'mood1_6month', 'mood2_6month', 'mood3_6month', 'dep1_6month', 'dep2_6month', 'dep3_6month']
If you are flexible on the ordering of the final list:
from itertools import product, imap
l1 = ['mood1', 'mood2', 'mood3', 'dep1', 'dep2', 'dep3']
l2 = ['pre', '6month']
x = list(imap('_'.join, product(l1, l2)))
This produces ['mood1_pre', 'mood1_6month', ...] rather than ['mood1_pre', 'mood2_pre', ...].