【问题标题】:Palindrome using Stack in Python在 Python 中使用 Stack 的回文
【发布时间】:2020-04-23 11:04:06
【问题描述】:

我正在尝试使用堆栈实现回文,但我被下面的代码卡住了。虽然我应该得到“真”,但我得到了“假”。你能帮我解决吗?

from Stack import Stack
import copy

def display(data):
    original= Stack()
    reverse= Stack()
    for i in range(len(data)):
        original.push(data[i])

    dat=copy.deepcopy( original)
#    print(hex(id(dat)))
#    print(hex(id(original)))

    for i in range(len(data)):
        a= original.pop()
        reverse.push(a)
#    original.disp()
    reverse.disp() #disp() shows elements in list form
    dat.disp()
    if dat == reverse:
        return True

    else:
        return False

print(display('racecar'))

【问题讨论】:

  • 分享你的Stack 实现
  • 谢谢@GrijeshChauhan,我想我发现了我的错误。显然我是在比较“堆栈”类的实例,而不是比较它们的列表。
  • 那么你应该发帖an answer to your own question

标签: python python-3.x stack palindrome


【解决方案1】:

如果您将单词前半部分的字母压入堆栈,您应该能够在将它们从堆栈中弹出时逐个字母地将它们与单词的其余部分进行比较。如果它们都匹配,则您有一个回文。无需手动反转列表(这会破坏使用堆栈的意义)或制作副本。两者都损害了效率。诀窍是区分奇数长度和偶数长度的单词,因为您不需要比较奇数长度单词的中间字母

由于您没有提供堆栈实现,我将只使用一个列表,但您应该能够看到它是如何工作的:

def pali(s):
    stack = []
    mid = len(s)//2

    # push first half of the word onto stack
    for c in s[:mid]:
        stack.append(c)

    # adjust mid for odd length words
    if len(s) % 2: 
        mid+=1

    # look at rest of the word while popping off the stack
    for c in s[mid:]:
        if stack.pop() != c:
            return False

    return True

print(pali("hello")) # False
print(pali("madamimadam")) # True

【讨论】:

    【解决方案2】:

    如果您想使用堆栈,如果您的输入实际上是一个 Python 序列(例如,listtuplestr 等),则考虑到 @MarkMeyer's answer 是正确的方法。检查回文的更紧凑和有效的方法是使用切片:

    def is_palindrome(seq):
        n = len(seq)
        m = n // 2
        q = m + n % 2 - 1
        return seq[:m] == seq[:q:-1]
    
    
    print(is_palindrome('ciao'))
    # False
    print(is_palindrome('aboba'))
    # True
    print(is_palindrome('abooba'))
    # True
    

    【讨论】:

      【解决方案3】:
      class Stack_structure:
         def __init__(self):
            self.items = []
      
         def check_empty(self):
            return self.items == []
      
         def push_val(self, data):
           self.items.append(data)
      
         def pop_val(self):
            return self.items.pop()
      
      my_instance = Stack_structure()
      text_input = input('Enter the string... ')
      
      for character in text_input:
         my_instance.push_val(character)
      
      reversed_text = ''
      while not my_instance.check_empty():
         reversed_text = reversed_text + my_instance.pop_val()
      
      if text_input == reversed_text:
         return True
      else:
      return False
      

      【讨论】:

        猜你喜欢
        • 2018-07-09
        • 1970-01-01
        • 2017-01-20
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-17
        • 2021-07-11
        • 2021-12-16
        相关资源
        最近更新 更多