+ 1

[Solved] As a beginner in python, I tried to solve THE SPY LIFE problem. Can anybody say what is wrong in my code?

msg = input() smsg = reversed(msg) valid = 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ' valist = list(valid) li = list(smsg) for l in li: if l in valist: continue else: li.remove(l) smsg = "".join(li) print(smsg) INPUT (case 2) : t`a=e+r8g 9e78r3a4 u^o%y* Expected output: you are great My output: you ar7e great

9th Jul 2021, 4:09 AM
Subashini G
Subashini G - avatar
8 Antworten
+ 4
when you iterate a list, and modify it, you continue iteration with the new list but with the old index... so in case of your example, you start at index 0 and you remove *, so now at index 0 is y... on next iteration you read index 1, wich is not the next initial char (y) but %... add a print statement inside your loop to view wich char is in l at each step ;) as a fix, you could iterate on a copy of the list, so modification of original will not affect char iterations: for l in li[:]: another way would be to use string, wich are imutable, and build a new string by concatenating valid char... in this case, to reverse the string, you could use msg[::-1], as reversed() return a list (your list(smsg) is pointless ;P) or keep a list to iterate, without copying it as you don't modify it (by building a new string instead)
9th Jul 2021, 4:29 AM
visph
visph - avatar
+ 3
Aysha providing another solution rather than correcting OP code would confuse him (all the more by introducing regular expressions) and not help him to understand what he missed in its solution ^^
9th Jul 2021, 4:32 AM
visph
visph - avatar
+ 2
visph Thank you so much bro. I understood what is wrong in my code.
9th Jul 2021, 4:38 AM
Subashini G
Subashini G - avatar
+ 1
Aysha that seems simpler way to you as you are aware of regular expression, but for a beginner it would be cryptic to understand, and not help him to acquire basics of languages ;) anyway, if OP is lazy, he would prefer copy pasting your answer rather than read my longer post and correct himself its solution ^^
9th Jul 2021, 4:38 AM
visph
visph - avatar
+ 1
happy to see you're not one of the lazy people wich prefer earning xp easily rather than really learning \o/
9th Jul 2021, 4:40 AM
visph
visph - avatar
+ 1
Here are two short-code possibilities: #1 import re print(re.sub("[^A-Za-z ]", "", input())[::-1]) #2 [print(x, end="") for x in input()[::-1] if x.isalpha()] # Hope this helps
10th Jul 2021, 4:56 AM
Calvin Thomas
Calvin Thomas - avatar