A Python algorithm beating 98.93% competitors
May 7, 2021
Something you can control, playing video games or coding, is what you need in a mysterious, unstable but boring life.
Something you can control, playing video games or coding, is what you need in a mysterious, unstable but boring life. Today I met an interesting question in a chat group.
Question: given certain two strings s and t, write a function to identify if t is an alphanumeric of s.
Input: s = "anagram", t = "nagaram"
def isAnagram(self, s: str, t: str) -> bool: # Define a default bool var to compute result = True # Take advantages of a default data structure, set, of Python set_tmp = set(s) # Elements if set_tmp == set(t): for i in set_tmp: # Counts result = result and (s.count(i) == t.count(i)) else: result = False return (result)
Time consumed: 48 ms, beating 98.93% Python programmers.
It mainly takes advantage of the built-in optimizations and features of
setto reduce operations and use Boolean operations to improve efficiency.
Making noises by pressing mechanic keyboards is quite comfortable for me for its obvious difference from a continuously changing life. In another word, the former one coming with certainty should be treated as one comforting entertainment.