0
Not sure why it works for some of the letters but not all of them for the secret message problem.
words = input() 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'] alpha_caps = ['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'] rev_alpha = ['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 x in words: if x in alphabet: y = alphabet.index(x) words = words.replace(x,rev_alpha[y]) if x in alpha_caps: y = alpha_caps.index(x) words = words.replace(x,rev_alpha[y]) print(words)
6 Réponses
+ 4
You can link your code:
click on the +, Insert Code, sort for My Code Bits, select your code
Don't modify the string while you are iterating it.
+ 3
Nick Accordino ,
have a look at the slightly reworked code, and also read the comments that are marked as numbers:
https://code.sololearn.com/ceQGky6sGxxK/?ref=app
+ 3
Nick Accordino ,
the reasons why your attempt is not working as expected are:
- as Lisa already mentioned, we need to create a new string for the output
- using replace() is not a good idea here, since the output may not be correct in all cases:
input: "at the end is z"
result should be: "zg gsv vmw rh a"
but it shows: "ag ghv vmw rh a"
^ ^
the reason of this behaviour is: (let's have a look at the first letter "a")
we are iterating over the input string. we detect the letter "a" and it will be replaced by the letter "z"
... iterating continues ...
finally we reach the last letter of the input string which is "z", that will be replaced by "a", but this will replace also the already processed first letter...
the replace() method modifies ALL characters in the string, not only the character at the current iteration position
+ 2
As I wrote in the initial comment, it didn't work as you were modifying the same string that you were iterating
+ 1
Thank you for the help. But you can you explain why my original code did not work? I'm trying to understand what went wrong and how the language works.
+ 1
Thank you for explaining that. I didn't realize that replace function would change all the characters. I understand now thank you.