I am working on a task where I need to sort and remove the duplicate letters in a string. I ended up with the function doing what I wanted but out of shear luck. I don't know why these lines of code produce different outputs. Could someone help me understand?
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
while i < len(sorted1) - 1:
if sorted1[i] == sorted1[i + 1]:
del sorted1[i + 1]
else:
i += 1
return sorted1
print(format_string("aretheyhere"))
['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']
['a', 'e', 'h', 'r', 't', 'y']
#This did what I wanted. but these seemingly similar lines don't.
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
j = i + 1
while i < len(sorted1) - 1:
if sorted1[i] == sorted1[j]:
del sorted1[j]
else:
i += 1
return sorted1
print(format_string("aretheyhere"))
['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']
['a', 'y']
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
while i < len(sorted1) - 1:
if sorted1[i] == sorted1[i + 1]:
del sorted1[i + 1]
i += 1
return sorted1
print(format_string("aretheyhere"))
['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']
['a', 'e', 'e', 'h', 'r', 't', 'y']
What are the crucial differences here that change the output?
The variable j doesn't increment because it's not updated inside your while loop, i.e. changing the value of i after setting the value of j to i+1 does not change the value of j. For example, this function would give the same result as the first one because the value of j is updated inside the while loop:
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
while i < len(sorted1) - 1:
j = i + 1
if sorted1[i] == sorted1[j]:
del sorted1[j]
else:
i += 1
return sorted1
print(format_string("aretheyhere"))
Related
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.
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']]
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)
I have two programs that are supposed to reverse a list of chars (strings with length 1). While the second program gives the correct output, the first one doesn't.
Here is program #1:
string = ['h', 'e', 'l', 'l', 'l', 'o']
y = len(string) / 2
for letter in string:
x = string.index(letter)
if x < y:
string[x], string[-1-x] = string[-1-x], string[x]
Here is program #2:
string = ['h', 'e', 'l', 'l', 'l', 'o']
y = len(string) / 2
x = 0
while x < y:
if x < y:
string[x], string[-1-x] = string[-1-x], string[x]
x += 1
My second program successfully reverses the string, but the first one returns ['o', 'e', 'l', 'l', 'l', 'h']. I'm glad I found a solution but would prefer to use .index() rather than counting each loop.
There is an anti-pattern in your first program.
x = string.index(letter)
Consider when you're indexing for the 2nd or 3rd 'l'... x will always be 2. The condition x < y will kick in and reverse the positions of 'e' and the second 'l'.
Here's some debugging:
(Notice that x is 2 at the second, third, and fourth iterations when it should be 2, 3, and 4 respectively.)
Iter 0:
letter = 'h'; x = 0; swap √; string = ['o', 'e', 'l', 'l', 'l', 'h']
# ^------------------------^
Iter 1:
letter = 'e'; x = 1; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
# ^--------------^
Iter 2:
letter = 'l'; x = 2; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
# ^----^
Iter 3: !
letter = 'l'; x = 2; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
# ^----^
Iter 4: !
letter = 'l'; x = 2; swap √; string = ['o', 'e', 'l', 'l', 'l', 'h']
# ^--------------^
Iter 5:
letter = 'l'; x = 5; swap X; string = ['o', 'e', 'l', 'l', 'l', 'h']
Pythonically, you should use enumerate to keep track of the index:
y = len(string) / 2
for i, _ in enumerate(string):
if i < y:
string[i], string[-1-i] = string[-1-i], string[i]
(An underscore was substituted for letter following PEP8 style guides.)
Or even better:
string = string[::-1]
I see that the variable "string" is list of strings. You can reverse it as simple as this:
string = ['h', 'e', 'l', 'l', 'l', 'o']
string.reverse()
string
This should print ['o', 'l', 'l', 'l', 'e', 'h']
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!