用于反向字符串代码的Python堆栈方法



我想在这个问题中使用堆栈方法来获得反向字符串。
写一个函数revstring(mystr),它使用堆栈来反转字符串中的字符。
这是我的代码

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")

输出似乎只输出mystr的第一个字母"m"为什么呢? ?

对于同样的问题,这里有3个解决方案,只要选择一个:

1解决方案

修复你的解决方案,你几乎得到了它,你只需要适当地缩进您的块像这样:

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():
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()
    return revstr
print revstring("martin")

2解决方案

这个在结构上与你的相同,但它没有使用自定义堆栈,而是使用内置的python列表

def revstring(mystr):
    myStack = [] # this is how i have myStack
    for ch in mystr:
        myStack.append(ch) # push the characters to form a stack
    revstr = '' # form an empty reverse string
    while len(myStack):
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()
    return revstr
print revstring("martin")

第三方案

要反转字符串,只需使用python方式:)

print "martin"[::-1]
  • while不应该在for
  • return应该在外面,而不是在while

代码:

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():
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()
    return revstr

print revstring("martin")

最新更新