Python 3.x 定义函数以查找给定字符串中的唯一回文
我对python有点陌生。我正在尝试定义一个函数,当被问到该函数时,它将只输出唯一的单词,这些单词是字符串中的回文 我使用Python 3.x 定义函数以查找给定字符串中的唯一回文,python-3.x,function,palindrome,Python 3.x,Function,Palindrome,我对python有点陌生。我正在尝试定义一个函数,当被问到该函数时,它将只输出唯一的单词,这些单词是字符串中的回文 我使用casefold()使其不区分大小写,并使用set()仅打印单号 这是我的密码: def uniquePalindromes(string): x=string.split() for i in x: k=[] rev= ''.join(reversed(i)) if i.casefold() == rev.ca
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'}
作为输出。请帮忙。如果我给你一些建议,他们不会喜欢我的。但是试着把字符的数量(不是空格)分成2。如果两边的金额不相等,那么你必须处理奇数个字母。这意味着您应该能够从中间向下和从中间向上遍历回文,将这些字母一起比较,并使用中间点作为“跳转”点。希望这有帮助您的逻辑是正确的,您的功能主要是做您希望它做的事情。问题的一部分是你如何返回东西——你所做的只是打印每个单词的集合。例如,当我获取您现有的代码并执行以下操作时:
>>> print(uniquePalindromes('Hannah Hannah Alomomola Girafarig Yes Nah, Chansey Goldeen Need log'))
{'hannah'}
{'alomomola'}
{'girafarig'}
None
hannah
、alomomola
和girafarig
是我希望看到的回文,但它们没有以我期望的格式给出。一方面,它们被打印出来,而不是退回,另一方面,这种情况一个接一个地发生
函数返回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)
现在,它返回的结果与您预期的大致相同——一个集合包含多个单词,而不是打印多个集合,每个集合包含一个单词。然后,我们就可以打印那套了
>>> 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'}
sarah
不是回文<代码>'sarah'!='哈拉斯。你不会退回任何东西的。空的“return”返回None
returnk
如果我正在处理的字符串中没有回文,是否有方法返回空集。我原以为使用return none
会有帮助,但它并没有按计划工作。@JBlack我的更新版本实际上可以做到这一点!尝试打印(唯一回文(“本句中没有回文”),它将打印set()
-一个空集。发生这种情况的原因是,如果没有回文,那么列表中就没有添加任何内容,因此我们从中创建的集合是空的。我正在尝试以相反的字典顺序打印集合,因此我将代码更改为:def uniquePalindromes(string):x=string.split()k=[]for I in x:rev=''.join(reversed(I))如果i.casefold()==rev.casefold():k.append(i.casefold())k=sorted(k,reverse=True)返回列表(set(k))
。但这是返回“安娜”,“汉娜”而不是“汉娜”,“安娜”。这是错误的做法吗?@JBlack将其放入集合
可能会打乱顺序。我会先从集合转换到列表,例如返回排序(list(set(k)),reverse=True)