Engineering | A Python algorithm beating 98.93% competitors

date
May 7, 2021
slug
algorithm-9893
status
Published
summary
Something you can control, playing video games or coding, is what you need in a mysterious, unstable but boring life.
tags
Engineering
Python
type
Post
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.
i.e.:
Input: s = "anagram", t = "nagaram"
Output: true
My answer:
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)
Result:
Time consumed: 48 ms, beating 98.93% Python programmers.
 
It mainly takes advantage of the built-in optimizations and features of set to 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.

RSS | Reynard © 2021 - 2023

Powered byVercel