Python Forum
anagram check with bitwise - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: anagram check with bitwise (/thread-18717.html)



anagram check with bitwise - itaybardugo - May-28-2019

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



RE: anagram check with bitwise - Gribouillis - May-28-2019

A serious problem is that anagram('silent', 'silens') returns True.