Reputation: 31
First post in here :)
So what I'm trying to achieve is, if a character is found inside a list in 'key' list then add the 'other' character in that list to the variable 's'. If a character is not found inside a list, then add the character itself to the variable 's'.
message="hello !"
s=""
found=False
key=[['m', 'c'], ['u', 'e'], ['b', 'g'], ['a', 'k'], ['s', 'v'], ['h', 'x'],['i', 'z'], ['r', 'y'], ['p', 'w'], ['l', 'n'], ['o', 'j'], ['t', 'f'], ['q', 'd']]
for i in message:
for j in key:
if i==j[0]:
found=True
s+=j[1]
break
elif i==j[1]:
found=True
s+=j[0]
break
if not found:
s+=i
return s
input:
hello !
expected output:
xunnj !
Somehow the later part(add the character itself to the 's' variable) does not work unless I put an else block to the first if statement. like this,
if i==j[0]:
found=True
s+=j[1]
break
elif i==j[1]:
found=True
s+=j[0]
break
else:
found=False
output without the else block:
xunnj
I want to know why,
if not found:
s+=i
does not work without an else block to the first if statement. Thanks.
Upvotes: 2
Views: 92
Reputation: 532418
This is much simpler using a dict
, and dict
s are easy to create given a list of iterables like key
is.
>>> d = dict(key)
>>> d.update(map(reversed, key))
>>> ''.join(d.get(x, x) for x in message)
'xunnj !'
Upvotes: 1
Reputation: 4389
You need to give found = False
every time you enter in the inner loop, otherwise it sets found = False
only once from the outside of all the loops, which is why if at any time in the inner loop found
become True
then it never become False
and remains True
for rest of the time, and that is why it never enter into if not found:
as found
remains True
always.
Your code should be like:
message="hello !"
s=""
# found=False
key=[['m', 'c'], ['u', 'e'], ['b', 'g'], ['a', 'k'], ['s', 'v'], ['h', 'x'],['i', 'z'], ['r', 'y'], ['p', 'w'], ['l', 'n'], ['o', 'j'], ['t', 'f'], ['q', 'd']]
for i in message:
found=False # use found here, cause you need to give `found = False` every time you enter in the inner loop, as in the inner loop you are considering found every time, so you need to set it from the outer loop
for j in key:
if i==j[0]:
found=True
s+=j[1]
break
elif i==j[1]:
found=True
s+=j[0]
break
if not found:
s+=i
print(s) # you may be want to print the `s` rather return
Output :
xunnj !
Upvotes: 1