Reputation: 13
I have two programs that are supposed to reverse a list of chars (strings with length 1). While the second program gives the correct output, the first one doesn't.
Here is program #1:
string = ['h', 'e', 'l', 'l', 'l', 'o']
y = len(string) / 2
for letter in string:
x = string.index(letter)
if x < y:
string[x], string[-1-x] = string[-1-x], string[x]
Here is program #2:
string = ['h', 'e', 'l', 'l', 'l', 'o']
y = len(string) / 2
x = 0
while x < y:
if x < y:
string[x], string[-1-x] = string[-1-x], string[x]
x += 1
My second program successfully reverses the string, but the first one returns ['o', 'e', 'l', 'l', 'l', 'h']
. I'm glad I found a solution but would prefer to use .index()
rather than counting each loop.
Upvotes: 0
Views: 137
Reputation: 8987
There is an anti-pattern in your first program.
x = string.index(letter)
Consider when you're indexing for the 2nd or 3rd 'l'
... x
will always be 2. The condition x < y
will kick in and reverse the positions of 'e'
and the second 'l'
.
Here's some debugging:
(Notice that x is 2 at the second, third, and fourth iterations when it should be 2, 3, and 4 respectively.)
Iter 0:
letter = 'h'; x = 0; swap √; string = ['o', 'e', 'l', 'l', 'l', 'h']
# ^------------------------^
Iter 1:
letter = 'e'; x = 1; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
# ^--------------^
Iter 2:
letter = 'l'; x = 2; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
# ^----^
Iter 3: !
letter = 'l'; x = 2; swap √; string = ['o', 'l', 'l', 'l', 'e', 'h']
# ^----^
Iter 4: !
letter = 'l'; x = 2; swap √; string = ['o', 'e', 'l', 'l', 'l', 'h']
# ^--------------^
Iter 5:
letter = 'l'; x = 5; swap X; string = ['o', 'e', 'l', 'l', 'l', 'h']
Pythonically, you should use enumerate
to keep track of the index:
y = len(string) / 2
for i, _ in enumerate(string):
if i < y:
string[i], string[-1-i] = string[-1-i], string[i]
(An underscore was substituted for letter
following PEP8 style guides.)
Or even better:
string = string[::-1]
Upvotes: 2
Reputation: 649
I see that the variable "string" is list of strings. You can reverse it as simple as this:
string = ['h', 'e', 'l', 'l', 'l', 'o']
string.reverse()
string
This should print ['o', 'l', 'l', 'l', 'e', 'h']
Upvotes: 0