I want to use the stack method to get reverse string in this revers question.
"Write a function revstring(mystr) that uses a stack to reverse the characters in a string."
This is my code.
from pythonds.basic.stack import Stack
def revstring(mystr):
myStack = Stack() //this is how i have myStack
for ch in mystr: //looping through characters in my string
myStack.push(ch) //push the characters to form a stack
revstr = '' //form an empty reverse string
while not myStack.isEmpty():
revstr = revstr + myStack.pop() //adding my characters to the empty reverse string in reverse order
return revstr
print revstring("martin")
the output seems to print out only the first letter of mystr that is "m" why this??
returnstatement is part of yourwhileblock. Which is itself part of yourforblock. In other words, your indentation needs work.#for comments, not//.whileloop is executed for each iteration of theforloop. Yourreturnends both thewhileand theforloop, because it is part of both.