Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String reversal only reverses half the string

Tags:

python

reverse

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?

like image 557
thektulu7 Avatar asked Jan 23 '26 12:01

thektulu7


2 Answers

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.

like image 56
Martijn Pieters Avatar answered Jan 25 '26 03:01

Martijn Pieters


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.

like image 44
Xoul Avatar answered Jan 25 '26 02:01

Xoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!