list out of range. Loop list in python - 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.

Related

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']]

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)

Print all possible strings of length k that can be formed from a set of n characters returns >n characters

Python novice here. The goal of the following Code is, to print all possible combinations to pair n characters of the set.
The Problem is that the following code gives an output, that also has more then n characters.
In the Following Code example n=3, but in the Output there are combinations with more then 3.
Code:
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
def printAllKLengthRec(set, prefix, n, k):
if (k == 0) :
print(prefix)
return
for i in range(n):
newPrefix = prefix + set[i]
printAllKLengthRec(set, newPrefix, n, k-1)
if __name__ == "__main__":
print("First Test")
set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S','T','V','W','Y']
k = 3
printAllKLength(set1, k)
Output:
WNT
WNV
WNW
WNY
WPQA
WPQC
WPQD
WPQE
WPQF
WPQG
WPQH
WPQI
WPQK
WPQL
WPQM
WPQN
WPQPQ
WPQR
WPQS
WPQT
WPQV
WPQW
WPQY
WRA
The aim would be to generate strictly strings of length 3, so if anyone could point me in the right direction, I would be more than grateful.
I rewrote you functions a bit and stripped them to the essentials:
def printAllKLength(set, k):
printAllKLengthRec(set, "", k)
def printAllKLengthRec(set, string, k):
if len(string) == k:
print(string)
return
for c in set:
printAllKLengthRec(set, string + c, k)
return
if __name__ == "__main__":
print("First Test")
set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K',
'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
k = 3
printAllKLength(set1, k)
A little hint for next time, break you sample size down to for example len(set1) = 3. then it is far easier to debug and you don't get lost in your own code.
You can use Itertools' combinations function. It takes an iterable and the length of the combination as parameters.
import itertools
num_char = 3
my_set = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}
combinations = itertools.combinations(my_set, num_char)
for i in combinations:
print("".join(i))

How to write code that checks to see if item is negative before split?

Hey so I have a polyalphabetic cipher and it's working great but I am running into the issue of having all my inputs on one line. The inputs would be the shift;secretWord; and message. I need to find a way to check if an input is solely a negative number and if it is I need the code to exit. I also need to find a way to make my code keep looping until the negative condition is met.
alpha = ['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']
shiftChange = 0
secretWord = 0
da_message = 0
shiftChange = int(shiftChange)
inputs = []
shiftChange, secretWord, da_message = input('').split(";")
da_message = da_message.lower()
inputs.append(shiftChange)
inputs.append(secretWord)
inputs.append(da_message)
secretWord = secretWord.lower()
secretWord = secretWord * len(da_message)
cypherText = ''
symbol = ' '
count = 0
for letter in da_message:
if letter in alpha:
shift = alpha.index(secretWord[count]) + int(shiftChange)
letterIndex = alpha.index(letter) + 1
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count + 1
print(cypherText.upper())
Use int().
The int() raises a ValueError for anything that isn't, entirely, an integer. Trap this error using a try-except loop and then if the error is raised, then execute the rest of your code. (since it is an alphanumeric) Otherwise, compare it if it is less than 0 and exit if true.
Below is a modified version of your code that solves both of your problems.
The while True ensures the program continues to loop until the negative number is found, which in turn causes it to exit the entire program.
alpha = ['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']
shiftChange = 0
secretWord = 0
da_message = 0
cypherText = ''
symbol = ' '
count = 0
shiftChange = int(shiftChange)
inputs = []
while True:
shiftChange, secretWord, da_message = input('enter:').split(";")
da_message = da_message.lower()
inputs.append(shiftChange)
inputs.append(secretWord)
inputs.append(da_message)
secretWord = secretWord.lower()
secretWord = secretWord * len(da_message)
for i in range(len(inputs)):
try:
temp = int(inputs[i])
except ValueError:
for letter in da_message:
if letter in alpha:
shift = alpha.index(secretWord[count]) + int(shiftChange)
letterIndex = alpha.index(letter) + 1
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count + 1
print(cypherText.upper())
if temp < 0:
exit()
Hope this helps!

Check if a string is in a list of letters - Python3

I have this list which contains letters, and I need to check if a pre-determined word located in another list is horizontally inside this list of letters.
i.e.:
mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']]
words_to_search = ['python', 'fox']
I don't need to tell if a word was not found, but if it was I need to tell which one.
My problem is that so far I've tried to compare letter by letter, in a loop similar to this:
for i in range(n): # n = number of words
for j in range(len(word_to_search[i])): # size of the word I'm searching
for k in range(h): # h = height of crossword
for m in range(l): # l = lenght of crossword
But it's not working, inside the last loop I tried several if/else conditions to tell if the whole word was found. How can I solve this?
You can use str.join:
mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']]
words_to_search = ['python', 'fox']
joined_input = list(map(''.join, mat_input))
results = {i:any(i in b or i in b[::-1] for b in joined_input) for i in words_to_search}
Output:
{'python': True, 'fox': False}
I'd start by joining each sublist in mat_input into one string:
mat_input_joined = [''.join(x) for x in mat_input]
Then loop over your words to search and simply use the in operator to see if the word is contained in each string:
for word_to_search in words_to_search:
result = [word_to_search in x for x in mat_input_joined]
print('Word:',word_to_search,'found in indices:',[i for i, x in enumerate(result) if x])
Result:
Word: python found in indices: [1]
Word: fox found in indices: []

Categories

Resources