1. What I learned
hash()
It returns the hash value of an object if it has one. Even if you give the same value as a variable, the hash value always changes with each run.
msg = "hello"
print(hash(msg))
# -3167519980713740997 (1st try)
# -1242044876459104822 (2nd try)
2. Code
class Codec:
def __init__(self):
self.dict = {}
def encode(self, longUrl: str) -> str:
shortUrl = hash(longUrl) # Create a hash value through hash()
self.dict[shortUrl] = longUrl
return shortUrl
def decode(self, shortUrl: str) -> str:
return self.dict[shortUrl]
3. Result
Runtime : 28 ms(90.43%), Memory usage : 14.1 MB(90.43%)
(Runtime can be different by a system even if it is a same code.)