如果单词的前半部分和后半部分包含完全相同的字母,但不一定以相同的顺序排列,则该单词就是amphisbaena。如果单词的字母数为奇数,则在这个定义中忽略中间字母(或者它属于两个半字母)。在
我的代码在大多数情况下都可以工作,除了使用“eisegesis”->;eise esis 我的代码不会检查所有字母是否只在另一个单词中出现一次唯一,反之亦然。字母“s”不会在单词的另一部分(一半)出现两次。如何调整代码?在
def amphisbaena(word):
"""
>>> amphisbaena('RESTAURATEURS')
True
>>> amphisbaena('eisegesis')
False
>>> amphisbaena('recherche')
True
"""
j = int(len(word) / 2)
count = 0
tel = 0
firstpart, secondpart = word[:j], word[-j:]
for i in firstpart.lower():
if i in secondpart.lower():
count +=1
for i in secondpart.lower():
if i in firstpart.lower():
tel +=1
if 2 * j == count + tel:
return True
else:
return False
你需要分别计算两半字母的数量,并比较每一个字母的数量。最简单的方法是使用
collections.Counter
:虽然这并不像比较排序的一半那么简单,但它是}。在
O(N)
,而不是{您可以在一行中使用lambda函数:
输出:
^{pr2}$其他字符串:
输出:
我会这样做的:
相关问题 更多 >
编程相关推荐