Python: checking if all letters in a nutshell are exactly the same, but not in the same order (amphisbaena)

A word is amphizbaena if the first half and the last half of the word contain exactly the same letters, but not necessarily in the same order. If the word has an odd number of letters, the middle letter is ignored in this definition (or it applies to both halves).

My code works in most cases, except, for example, with: 'eisegesis' → eise esis My code does not check if all letters appear ONLY ONE TIME in another word and vice versa. The letter 'does not appear twice in another part (half) of the word. How can I customize my code?

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
+4
source share
3 answers

. 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) O(N * log_N).

+3

- :

j = int(len(word) / 2)

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

You can do with the lambda function in one line:

   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))

output:

True

With another line:

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))

output:

False
0
source

Source: https://habr.com/ru/post/1688411/


All Articles