forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sol.py
49 lines (40 loc) · 1.57 KB
/
sol.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
class URLShortener:
def __init__(self):
self.url_store = {}
self.urls_shortened = 1000000000 #assume 1000000000 URLs have been already registered
def shorten(self, url):
self.urls_shortened+=1
self.url_store[self.urls_shortened] = url
num_b62 = self.convertToBase(self.urls_shortened, 62)
return ''.join(self.numToChar[i] for i in num_b62)
def restore(self, short):
num_b62 = [self.charToNum[char] for char in short]
num = self.convertToDecimal(num_b62, 62)
return self.url_store[num]
@staticmethod
def convertToBase(n: int, base: int) -> list:
A = []
while n:
A.append(n%base)
n//=base
return A
@staticmethod
def convertToDecimal(num_base: list, base: int) -> int:
num = 0
for i, digit in enumerate(num_base):
factor = base**i
num+=factor*digit
return num
@property
def charToNum(self):
return {letter: i for i, letter in enumerate(ALLOWED_CHARS)}
@property
def numToChar(self):
return {i: letter for i, letter in enumerate(ALLOWED_CHARS)}
if __name__=='__main__':
shortener = URLShortener()
short1 = shortener.shorten('https://medium.freecodecamp.org/the-art-of-computer-programming-by-donald-knuth-82e275c8764f')
short2 = shortener.shorten('https://www.youtube.com/watch?v=Pt0nqbSJiEE')
print(short1, shortener.restore(short1))
print(short2, shortener.restore(short2))