在Python中使用堆栈的回文

问题描述 投票:0回答:2

我正在尝试使用堆栈来实现回文,但是我被下面的代码所困扰。虽然我应该得到“正确”,但我却得到“错误”。你能帮我吗?

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'))
python python-3.x stack palindrome
2个回答
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

0
投票

鉴于如果您想使用堆栈,并且您的输入实际上是Python序列(例如@MarkMeyer's answerlisttuple等),则str是正确的处理方式检查切片的更紧凑,更有效的方法是使用切片:

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
© www.soinside.com 2019 - 2024. All rights reserved.