定义用于在给定字符串中查找唯一回文的函数

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

我是python的新手。我正在尝试定义一个函数,当被询问时将仅输出字符串中回文的唯一单词。

我使用casefold()使其不区分大小写,并且set()仅打印不重复。

这是我的代码:

def uniquePalindromes(string):
    x=string.split()
    for i in x:
        k=[]
        rev= ''.join(reversed(i))
        if i.casefold() == rev.casefold():
            k.append(i.casefold())
            print(set(k))
        else:
            return

我尝试运行此行

print( uniquePalindromes('Hanah asked Sarah but Sarah refused') )

期望的输出应为['hanah','sarah'],但仅返回{'hanah'}作为输出。请帮助。

python-3.x function palindrome
2个回答
0
投票

如果我给你一些提示,他们不会喜欢我的。但是,请尝试将字符数(不是空格)分成2个。如果两边的字符数不相等,则您必须处理奇数个字母。这意味着您应该能够遍历从中间向下和从中间向上的回文,将这些字母一起比较,并将中间点用作“跳出”点。希望对您有所帮助


0
投票

您的逻辑是正确的,并且您的功能主要在执行您想要的。问题的一部分在于您如何returning事情-您所做的只是打印每个单词的集合。例如,当我采用您现有的代码并执行此操作时:

>>> print(uniquePalindromes('Hannah Hannah Alomomola Girafarig Yes Nah, Chansey Goldeen Need log'))
{'hannah'}
{'alomomola'}
{'girafarig'}
None

hannahalomomolagirafarig是我希望看到的回文,但是没有以我期望的格式给出。首先,它们是printed,而不是returned,而对于两个,它们是一个接一个地发生。]

并且该函数返回None,而您正在尝试打印它。这不是我们想要的。


这是函数的固定版本:

def uniquePalindromes(string):
    x=string.split()
    k = []  # note how we put it *outside* the loop, so it persists across each iteration without being reset
    for i in x:
        rev= ''.join(reversed(i))
        if i.casefold() == rev.casefold():
            k.append(i.casefold())  
            # the print statement isn't what we want
        # no need for an else statement - the loop will continue anyway
    # now, once all elements have been visited, return the set of unique elements from k
    return set(k)

现在它将大致返回您的期望-一个包含多个单词的single

集,而不是打印每个包含一个单词的多个集。然后,我们可以打印该集合。
>>> print(uniquePalindromes("Hannah asked Sarah but Sarah refused"))
{'hannah'}
>>> print(uniquePalindromes("Hannah and her friend Anna caught a Girafarig and named it hannaH"))
{'anna', 'hannah', 'girafarig', 'a'}
© www.soinside.com 2019 - 2024. All rights reserved.