反字符串cod的python堆栈方法

2024-09-28 01:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用stack方法在这个反向问题中得到反向字符串。
“编写一个函数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” 为什么这样??在


Tags: 函数字符串instringstackmychpush
2条回答

这里有3个解决相同问题的方法,只需选择一个:

第一个解决方案

修正你的解决方案,你几乎得到了,你只需要适当地缩进 你的街区像这样:

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

第二个解决方案

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

^{pr2}$

第三种解决方案

要反转字符串,只需使用这种python方法:)

print "martin"[::-1]
  • while不应在for
  • {cd3>不应该在外面

代码:

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

相关问题 更多 >

    热门问题