在python中使用堆栈机检查反转字符串是否为回文的程序
你能帮我解决以下问题吗 我试图从用户那里获得一个字符串输入,然后将字符串推入堆栈机,以检查字符串的有效性。如果字符串通过了定义的规则,那么将检查StackMachine的输出字符串是否为回文..这就是我到目前为止所尝试的 注意您只能使用StackMachine类中的函数,而不能使用其他方法来确定字符串的有效性。接受字符串的条件是您已读取所有输入字符串,并且堆栈为空在python中使用堆栈机检查反转字符串是否为回文的程序,python,list,data-structures,stack,Python,List,Data Structures,Stack,你能帮我解决以下问题吗 我试图从用户那里获得一个字符串输入,然后将字符串推入堆栈机,以检查字符串的有效性。如果字符串通过了定义的规则,那么将检查StackMachine的输出字符串是否为回文..这就是我到目前为止所尝试的 注意您只能使用StackMachine类中的函数,而不能使用其他方法来确定字符串的有效性。接受字符串的条件是您已读取所有输入字符串,并且堆栈为空 ``` class StackMachine(object): SMRules = {} # dictionary o
```
class StackMachine(object):
SMRules = {} # dictionary of SM rules
def __init__(self):
self.Stack = ['S'] # populate stack with initial 'S'
self.size = 1 # set size of stack to 1
self.SMRules = {} # Place rules here
def pop(self):
if len(self.Stack) <1:
pass
else:
self.Stack.pop(0)
self.size-= 1 # reduce stack size by 1
return
def peek(self):
ss = ""
if len(self.Stack) < 1:
return ""
else:
ss = self.Stack
return ss[0]
def stackIsEmpty(self):
if len(self.Stack) == 0:
return True
else:
return False
def push(self,str):
sStr = str[::-1] # slicing
for chr in sStr:
self.Stack.insert(0,chr) # push string onto top of stack
self.size = len(self.Stack)
return
def printStack(self):
print("Stack: [",end='')
for item in self.Stack:
print(item,end='')
print("]")
return
def printRules(self):
print("SM Rules:")
rn = 1
for key, value in self.SMRules.items():
print("Rule",rn,"%4s" % key,"|", value)
rn += 1
return
def main():
Stk = StackMachine()
text =str(input('Please enter the string: '))
for character in text:
Stk.push(character)
reversed_text = ''
while not Stk.stackIsEmpty():
reversed_text = reversed_text + Stk.pop()
if text == reversed_text:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')
if __name__ == '__main__':
main()
我的问题是
1.如何解决错误?
2.如何从stackMachine按字符打印字符串字符
3.成功检查堆栈计算机处理的字符串是否为回文。如定义,
StackMachine.pop()
返回None
当您执行reversed\u text+Stk.pop()
操作时,即使reversed\u text
是一个字符串,Stk.pop()
是None
,这会导致您看到的类型错误
为什么需要使用所谓的StackMachine
类来检查字符串是否是回文?有更简单的方法来检查字符串是否是回文
如果您只想获得一个字符串输入并确定它是否是回文,您可以这样做:
text = input()
isPalindrome = text == text[::-1]
给定的条件是必须使用StackMachine验证在哪里进行?如何将()用户提示的字符串推入StackMachine并在StackMachine验证后逐个字符打印该字符串StackMachine验证用户提示的字符串并检查其是否有效,根据StackMachine类或printRules()函数中定义的SM{}规则。。am所需要的只是编写代码,提示用户输入字符串,然后将字符串推送到计算机,然后请求计算机打印堆栈中的反向字符串,最后检查字符串是否为回文。列表可以作为后进先出结构,否则称为堆栈。查看list.append()
,将内容(包括字符)推送到列表末尾(链接:)。您可以按如下方式反转字符串,text
:text[::-1]
。这叫做切片。有关切片的详细信息:。
text = input()
isPalindrome = text == text[::-1]