Python Forum
anagram check with bitwise
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
anagram check with bitwise
#1
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"))
Reply
#2
A serious problem is that anagram('silent', 'silens') returns True.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Anagram Solver with Python BlazingWarlord 2 2,745 May-29-2021, 04:14 AM
Last Post: BlazingWarlord

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020