我想用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” 为什么这样??在
这里有3个解决相同问题的方法,只需选择一个:
第一个解决方案
修正你的解决方案,你几乎得到了,你只需要适当地缩进 你的街区像这样:
第二个解决方案
这一个在结构上与您的相同,但是它没有使用自定义堆栈,而是使用了内置的python列表
^{pr2}$第三种解决方案
要反转字符串,只需使用这种python方法:)
while
不应在for
中代码:
相关问题 更多 >
编程相关推荐