I am trying to reverse a word using stack and pop()
, I believe I am overlooking something.The idea is to have all the elements of the word in a new list, then pop them and have them in the original list. For a sample word to work with, you can use "rotate". Below is my attempt at solving it.
def revbystack(x):
stack = []
for i in range(len(x)):
stack.append(x[i])
for i in range(len(x)):
x[i] = stack.pop()
word = "rotate"
nw3 = list(word)
revbystack(nw3)
You problem is indentation. The nested for loop is executed for every iteration in outer for loop.
De-dent the nested for-loop:
def revbystack(x):
stack = []
for i in range(len(x)):
stack.append(x[i])
for i in range(len(x)):
x[i] = stack.pop()
word = "rotate"
nw3 = list(word)
revbystack(nw3)
print(nw3) # ['e', 't', 'a', 't', 'o', 'r']