Python Forum

Full Version: anagram check with bitwise
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi guys, iv'e just wrote a tiny program to check for anagram, using bitwise instead arrays
(anagram returns True if in case that 2 given strings have the same characters in different positions)

do you think it's better than using an array?
did i miss something or maybe there are things that i didn't take into consideration?


p.s
i assuming that its ok if string1="silent" and string2="silent".

CODE:
def anagram(s1, s2):
    check = 0
    check |= 1 << len(s1)
    try:
        if check & 1 or not check & (1 << len(s2)):  # one of s1 or s2 is empty. or they have different length
            raise Exception()

        check &= 0  # reset check
        for c in s1:
            check |= 1 << ord(c)  # shift left for each char

        for c in s2:
            if not check & (1 << ord(c)):  # char does not exists
                print(c)
                raise Exception()
    except:
        return False
    else:
        return True

print(anagram("listen", "silent"))
print(anagram("lsisten", "silents"))
A serious problem is that anagram('silent', 'silens') returns True.