0

Bug in reverse alphabet code

The code works in general except when a letter replaced by a letter and then followed by the same letter. Then it "skips" that letter. I don't understand where the problem is. For example input "piz" outputs "kra" which is correct. But input "pizza" outputs "krzzz" which is wrong. dict = {"a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"} x = input() for i in x: x = x.replace(i, dict.get(i)) print(x),

9th Apr 2022, 11:26 AM
Walter Zwiekhorst
Walter Zwiekhorst - avatar
4 Answers
+ 2
I came up with this alternative solution :) x =Ā input().lower() result =Ā "" Ā  alph =Ā ["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"] revalph = alph[::-1] Ā  forĀ iĀ inĀ x: Ā  Ā Ā ifĀ iĀ inĀ alph: Ā  Ā  Ā  Ā  ind = alph.index(i) Ā  Ā  Ā  Ā  result += revalph[ind] Ā  Ā Ā else: Ā  Ā  Ā  Ā  result += i Ā  Ā  Ā  Ā  print(result)
9th Apr 2022, 11:55 AM
Walter Zwiekhorst
Walter Zwiekhorst - avatar
+ 2
alph = list(map(chr, range(ord('a'), ord('z')+1))) # Alphabet a to z
9th Apr 2022, 1:02 PM
SoloProg
SoloProg - avatar
+ 1
Wow so you typed all the keys and values šŸ˜Š Thats a lot of work, find a work around Back to the question Okay so the thing is replace replaces all the duplicates So what you need to do is, pass the second parameter of replace so In general the syntax of replace is .replace(new, old, count) So you can specify a count which is, 1 in your case to affect just one character
9th Apr 2022, 11:42 AM
Faisal Issaka
Faisal Issaka - avatar
+ 1
Okay thats a bit okay
9th Apr 2022, 12:02 PM
Faisal Issaka
Faisal Issaka - avatar