I wanted to write a function that mirrors a string without using any built in functions and only using a loop.
For example, wordMirror("stackexchange") returns 'stackexchangeegnahcxekcats'.
I wrote the following code using some hints from my previous questions:
def wordMirror(word):
c = ""
for x in word:
c = c + x
return word + c
But it didn't work. I then started to play around with it and just reversed c = c + x to c = x + c and it magically worked.
What exactly is the code reading when I switched the variables?
There is nothing magic about it, the order in which your are adding characters to c is reversed because you are inserting x before what was previously in c.
You should really step through a run by hand:
iteration | x | c
-------------------------------
0 '' ''
1 s s
2 t ts
3 a ats
4 c cats
5 k kcats
6 e ekcats
7 x xekcats
8 c cxekcats
9 h hcxekcats
10 a ahcxekcats
11 n nahcxekcats
12 g gnahcxekcats
13 e egnahcxekcats
From this simple table you should be able to see how the string is growing. Learning how to execute your programs by hand is a vital skill to have.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With