forked from subsr97/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathurl-shortener.py
64 lines (50 loc) · 1.65 KB
/
url-shortener.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
#55
Microsoft
This problem was asked by Microsoft.
Implement a URL shortener with the following methods:
shorten(url), which shortens the url into a six-character alphanumeric string, such as zLg6wl.
restore(short), which expands the shortened string into the original url. If no such shortened string exists, return null.
Hint: What if we enter the same URL twice?
"""
import secrets
URLDict = dict()
alphabets = "abcdefghijklmnopqrstuvwxyz"
numbers = "0123456789"
alnum = list(alphabets+alphabets.upper()+numbers)
def createShortURL():
shortURL = ""
while shortURL == "":
while len(shortURL) < 6:
shortURL += secrets.SystemRandom().choice(alnum)
if shortURL in URLDict.keys():
shortURL = ""
return shortURL
def shortenNonRedundant(newLongURL):
for shortURL in URLDict.keys():
if URLDict[shortURL] == newLongURL:
return shortURL
newShortURL = createShortURL()
URLDict[newShortURL] = newLongURL
return newShortURL
def shortenRedundant(newLongURL):
newShortURL = createShortURL()
URLDict[newShortURL] = newLongURL
return newShortURL
def restore(shortURL):
if shortURL in URLDict.keys():
return URLDict[shortURL]
else:
return None
def main():
URLs = ["www.facebook.com", "www.google.com", "www.facebook.com"]
print("Non-redundant Shortening:")
for URL in URLs:
shortURL = shortenNonRedundant(URL)
print(shortURL,"-",restore(shortURL))
print("\nRedundant Shortening:")
for URL in URLs:
shortURL = shortenRedundant(URL)
print(shortURL,"-",restore(shortURL))
if __name__ == "__main__":
main()