Python:检查两个单词中的所有字母是否完全相同但顺序不同(amphisbaena)

2024-09-30 08:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如果单词的前半部分和后半部分包含完全相同的字母,但不一定以相同的顺序排列,则该单词就是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

Tags: 代码infalsetrueifcount字母单词
3条回答

你需要分别计算两半字母的数量,并比较每一个字母的数量。最简单的方法是使用collections.Counter

def amphisbaena(word):
    from collections import Counter
    w = word.lower()
    half = len(word) // 2
    return half == 0 or Counter(word[:half]) == Counter(word[-half:])

虽然这并不像比较排序的一半那么简单,但它是O(N),而不是{}。在

您可以在一行中使用lambda函数:

   string_1='recherche'

    half=int(len(string_1)/2)

    amphisbaena=lambda x: True if sorted(x[:half])==sorted(x[-half:]) else False
    print(amphisbaena(string_1))

输出:

^{pr2}$

其他字符串:

string_1='eisegesis'

half=int(len(string_1)/2)

amphisbaena=lambda x: True if sorted(x[:half])==sorted(x[-half:]) else False
print(amphisbaena(string_1))

输出:

False

我会这样做的:

j = int(len(word) / 2)

firstpart, secondpart = word[:j], word[-j:]
return sorted(firstpart) == sorted(secondpart)

相关问题 更多 >

    热门问题