Reputation: 45
I know I could just use the reverse
function to reverse a string, but for a Codecademy assignment I'm attempting to reverse a string without reverse
or [::-1]
. In attempting to find out what's wrong with my code, I've stumbled upon possible solutions to the problem, but at this point, I just want to understand what my code is doing.
def reverse(text):
text2 = list(text)
backwards = []
for char in text2:
backwards.append(text2[-1])
del(text2[-1])
return "".join(backwards)
text = raw_input("Say something:\n")
print reverse(text)
When I test this, the output is always the last half of the string reversed. I don't understand why for char in text2:
would be interpreted as for half_the_char in text2
. What about my code accounts for that oddity?
Upvotes: 3
Views: 2004
Reputation: 1123500
You are looping over the list and removing from it. So by the time you get to the halfway point, the second half of the list is gone and the for
loop stops because there are no more items to iterate over anymore.
Print out your list each iteration and you'll see what is happening:
>>> text2 = list('hello')
>>> backwards = []
>>> for char in text2:
... backwards.append(text2[-1])
... del text2[-1]
... print 'char:', char, 'backwards:', backwards, 'text2:', text2
...
char: h, backwards: ['o'] text2: ['h', 'e', 'l', 'l']
char: e, backwards: ['o', 'l'] text2: ['h', 'e', 'l']
char: l, backwards: ['o', 'l', 'l'] text2: ['h', 'e']
The for
loop then stops, because there is no more items to iterate over left; after iterating over indexes 0
, 1
and 2
, the list has been shortened to the point where there is no index 3
anymore.
You could use a while
loop instead:
while text2:
backwards.append(text2[-1])
del(text2[-1])
Now the loop only stops when text2
is entirely empty.
Or you could loop over text
, which has the same length and the same characters in it; it is almost as pointless as your original for
loop because you ignore the char
loop target just the same:
for char in text:
backwards.append(text2[-1])
del(text2[-1])
but text
at least is not being shortened as you loop, so your iteration doesn't end prematurely.
Or you could use a separate index to pick the character to add, adjusting it each iteration, and then not delete from text2
:
index = -1
for character in text2:
backwards.append(text2[index])
index -= 1
Now you'll iterate len(text2)
times. Of course, you then don't need to convert text
to a list anymore, you could just index into text
.
Upvotes: 4
Reputation: 369
You are deleting the values from the original list
del(text2[-1])
Let's consider an example string "star", index would be 0-3. In first iteration, you add 'r' to backwards list and then delete 'r' (last character) from original list, so now you have "sta" string left, but your number of iterations are reduced to 3. Loop keeps deleting and reducing list size, resulting in less iterations. This causes earlier termination of loop.
Upvotes: 2
Reputation: 114440
The line del(text2[-1])
accounts for your oddity. You are setpping along every character, but for every character you step, you delete one from the end, so your string will have nothing more left once you get half way through.
Rather than deleting the original characters, prepend the one you are iterating over:
for char in text2:
backwards.insert(0, char)
See this question for reference: What's the idiomatic syntax for prepending to a short python list?
Another option is to iterate over the string backwards and append to the list:
for i in range(len(text2)):
backwards.append(text2[-(i + 1)])
Upvotes: 0