Python newspace persists - python

I'm trying to make a name generator:
from random import randint
relation = {
'A' : ['B', 'C', 'D', 'F', 'R', 'Y'],
'B' : ['E', 'O', 'I'],
'C' : ['A', 'E', 'H', 'R', 'O', 'I'],
'D' : ['A', 'E', 'H', 'R', 'O', 'I'],
'E' : ['R', 'T', 'P', 'S', 'F', 'L', 'X'],
'F' : ['E', 'U', 'I', 'O', 'A'],
'G' : ['R', 'O', 'A'],
'H' : ['E', 'I', 'O', 'A'],
'I' : ['N', 'X', 'S', 'E', 'T', 'P', 'L', 'M'],
'J' : ['A', 'I', 'O', 'Y'],
'K' : ['I', 'E', 'A'],
'L' : ['I', 'E'],
'M' : ['O', 'Y', 'I'],
'N' : ['E', 'I', 'O', 'A'],
'O' : ['V', 'T', 'N'],
'P' : ['I', 'A', 'E', 'O'],
'Q' : ['U', 'E', 'I'],
'R' : ['E', 'I', 'A'],
'S' : ['T', 'I', 'O', 'A', 'H'],
'T' : ['H', 'E', 'I'],
'U' : ['B', 'G', 'L'],
'V' : ['E', 'U', 'I', 'A'],
'X' : ['I', 'O'],
'Y' : ['E', 'L'],
'Z' : ['O', 'I']
}
char = (raw_input("Enter an English alphabet: ")).upper()
letters = int(raw_input("How many letters: "))
for i in range(0, letters):
if i==0:
print char,
else:
print char.lower(),
char = (relation[char])[randint(0, len(relation[char])-1)]
print ''
raw_input("Press [ENTER] to exit...")
But the problem is that there is a whitespace when it prints the name.
For example:
Enter an English alphabet: T
How many letters: 5
T i p a y
Press [ENTER] to exit...
How to remove the whitespace?
P.S: I'm a beginner :)

It's the commas that's causing this. print statements separated with commas add white spaces:
print "a", "b"
Prints a b
print "a",
Prints a  (with white space)
print "a"
Prints a (without white space)
You can, however, change your code to use a variable:
name = ''
for i in range(0, letters):
if i==0:
name += char
else:
name += char.lower()
char = (relation[char])[randint(0, len(relation[char])-1)]
print name
print ''
Or shorter and more efficient:
letter_list = []
for i in range(0, letters):
letter_list.append(char)
char = (relation[char])[randint(0, len(relation[char])-1)]
name = ''.join(letter_list)
print name.lower().capitalize()
print ''

I am not exactly sure your reasoning for printing as you go along, but you could have a word variable and then append all the char you come up with to the word variable and just print it at the end. This will not have the spaces in between the letters
word = ''
for i in range(0, letters):
word += char
char = (relation[char])[randint(0, len(relation[char])-1)]
print word.lower().capitalize()
print ''
Based on PM 2 Rings suggestion you could also do it this way:
charList = []
for i in range(0, letters):
charList.append(char)
char = (relation[char])[randint(0, len(relation[char])-1)]
print ''.join(charList).lower().capitalize()
print ''

Related

list out of range. Loop list in python

Can you please help me with my problem ? in line 28 says list index out of range.
I tried change for i in list to for i in range(len(message)) but it didn't help.
Thanks for help
letter = [
'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',
]
falseletters = [
'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',
]
message = [
]
def writing():
print("start writing")
print("write ,,end'' to end")
x = True
while x:
b = input(">>")
if b == 'end':
x = False
nour = 0
for i in range(len(message)):
nour = nour + 1
check = message[nour]
if check in [falseletters]:
print(falseletters[nour])
if check not in [falseletters]:
print(check)
if b != 'end':
message.append(b)
print("added", b)
writing()
There's several errors in your code: however, the core of your problem I believe lies in the fact that you're not iterating over each letter over each word in the message list, rather you're checking if any of the words is in falseletters. Here's a working example of what I believe you're trying to accomplish:
letters = "abcdefghijklmnopqrstuvwxyz"
falseletters = "rstuvwxyzabcdefghijklmnopq"
def mapper(letter: str) -> str:
return falseletters[letters.index(letter)]
message = []
def writing():
print("start writing")
print("write ,,end'' to end")
x = True
while x:
b = input(">>")
if b == "end":
x = False
for check in message:
print("".join(map(mapper, check)))
else:
message.append(b)
print("added", b)
writing()
It takes each word in message, and maps each letter of the word to the false letter. Then, each mapped character is printed as a string.

How to convert a Python string in a list using no libraries

I'm trying to convert a string into a list wherever there is a bracket and using no libraries. So a string like '[wewr[sfs]]' should return ['w','e','w','r',['s','f','s']]. I'm not looking for a solution, just some guidance or advice over what is wrong with my code, the outcome I'm getting so far is ['w']
def my_function(s):
final_list = []
if d[0] == '[' and d[-1] == ']':
for i in d:
if i == '[':
final_list.append(my_function(d[(d.index('[')+1):(d.rindex(']'))]))
i = d(d.rindex(']') +1)
continue
elif i == ']':
break
else:
final_list.append(i)
return final_list```
You just have to think carefully about if-else-conditions:
def string_to_list(my_str):
out = []
for s in my_str.split('['):
if ']' in s[:-1]:
s1 = s.split(']')
s1 = [list(s1[0])]+list(s1[1])
elif s[-1:] == ']':
s1 = [list(s.strip(']'))]
else:
s1 = list(s)
out.extend(s1)
return out
print(string_to_list('[wewr[sfs]]'))
print(string_to_list('[wewr[sfs]da]'))
print(string_to_list('[wewr[sfs]da[ds]]'))
print(string_to_list('[wewr[sfs]da[ds][dfd]]'))
Output:
['w', 'e', 'w', 'r', ['s', 'f', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a']
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's']]
['w', 'e', 'w', 'r', ['s', 'f', 's'], 'd', 'a', ['d', 's'], ['d', 'f', 'd']]

Checking For Every Letter

I am trying to make code that breaks a password that I create, at first I got it to just make random answers to the password I created and eventually I would get the right one.
But I realized that if I could change the first letter of my answer and then when I had done all of the letters, change the second letter.
Ex: AA AB AC ... AY AZ BA BB BC.
I understand that I could make a loop to print every single letter, but how would I be able to change the first letter after I have gone through every letter.
I also need this to be able to break a password of any length so the loop would have to be able to change how many letters I need. I also need to get rid of the brackets and quotes in the output.
lower_upper_alphabet = ['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']
while done == 0:
for i in range (int(passwordlen)):
for i in range(52):
for i in range(len(lower_upper_alphabet)):
characters2 = []
characters2.append(str(lower_upper_alphabet[next1]))
next1 += 1
print(characters2)
Output:
["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"]

TypeError: can only concatenate str (not "int") to str (I don't think that should happen)

I decided it would be a cool idea to make a translator to a custom language, so I tried making one. However, I am fairly new to python, and I cannot figure out why it is expecting a string instead of an integer. What I am trying to do is make it so if you enter in a word such as 'bin', it will go to the next consonant/vowel for each, so 'bin' ends up as 'cop' as the next consonant after 'b' is 'c', the next vowel after 'i' is 'o' and the next consonant after 'n' is 'p'.
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
translated_word = ''
word_to_translate = input('Enter in the word to translate! ')
for letter in range(len(word_to_translate)):
new_letter = word_to_translate[letter - 1]
if new_letter in consonants:
l = (consonants[:new_letter + 1])
translated_word = translated_word + str(l)
elif new_letter in vowels:
l = (vowels[:new_letter + 1])
translated_word = translated_word + str(l)
print(translated_word)
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
translated_word = ''
word_to_translate = input('Enter in the word to translate! ')
for i in word_to_translate:
if i in consonants:
ind = consonants.index(i)
translated_word += consonants[ind+1]
elif i in vowels:
ind = vowels.index(i)
translated_word += vowels[ind+1]
print (translated_word)

Python: using indices and str

I am attempting to learn Python and am working on an assignment for fun that involves translating "encrypted" messages (it's just the alphabet in reverse). My function is supposed to be able to read in an encoded string and then print out its decoded string equivalent. However, as I am new to Python, I find myself continually running into a type error with trying to use the indices of my lists to give the values. If anyone has any pointers on a better approach or if there is something that I just plain missed, that would be awesome.
def answer(s):
'''
All lowercase letters [a-z] have been swapped with their corresponding values
(e.g. a=z, b=y, c=x, etc.) Uppercase and punctuation characters are unchanged.
Write a program that can take in encrypted input and give the decrypted output
correctly.
'''
word = ""
capsETC = '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',\
' ', '?', '\'', '\"', '#', '!', '#', '$', '%', '&', '*', '(', \
') ', '-', '_', '+', '=', '<', '>', '/', '\\'
alphF = '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'
alphB = 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm',\
'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'
for i in s:
if i in capsETC: # if letter is uppercase or punctuation
word = word + i # do nothing
elif i in alphB: # else, do check
for x in alphB: # for each index in alphB
if i == alphB[x]: # if i and index are equal (same letter)
if alphB[x] == alphF[x]: # if indices are equal
newLetter = alphF[x] # new letter equals alpf at index x
str(newLetter) # convert to str?
word = word + newLetter # add to word
print(word)
s = "Yvzs!"
answer(s)
your code is fine, just a few changes (left your old lines as comments)
def answer(s):
word = ""
capsETC = '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',\
' ', '?', '\'', '\"', '#', '!', '#', '$', '%', '&', '*', '(', \
') ', '-', '_', '+', '=', '<', '>', '/', '\\'
alphF = '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'
alphB = 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm',\
'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'
for i in s:
if i in capsETC: # if letter is uppercase or punctuation
word = word + i # do nothing
elif i in alphB: # else, do check
for x in range(len(alphB)): # for each index in alphB
if i == alphB[x]: # if i and index are equal (same letter)
# if alphB[x] == alphF[x]: # if indices are equal
newLetter = alphF[x] # new letter equals alpf at index x
# str(newLetter) # convert to str?
word = word + newLetter # add to word
return word
s = "Yvzs!"
print(s)
print(answer(s))
ouput
Yvzs!
Yeah!
of course you can make it a lot simple and python's way... but wanted to change your code as little as possible
Your current issue is that you are trying to use letters as indices. To fix your current approach, you could use enumerate while looping through each of your strings.
If you want a much simpler approach, you can make use of str.maketrans and str.translate. These two builtin functions help easily solve this problem:
import string
unenc = string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz
decd = unenc[::-1] # zyxwvutsrqponmlkjihgfedcba
secrets = str.maketrans(unenc, decd)
s = "Yvzs!"
print(s.translate(secrets))
Output:
Yeah!
If you want a looping approach, you can use try and except along with string.index() to achieve a much simpler loop:
import string
unenc = string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz
decd = unenc[::-1] # zyxwvutsrqponmlkjihgfedcba
s = "Yvzs!"
word = ''
for i in s:
try:
idx = unenc.index(i)
except:
idx = -1
word += decd[idx] if idx != -1 else i
print(word)
Output:
Yeah!

Categories

Resources