Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class URLShortener:
- def __init__(self):
- self.base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
- self.b = 62
- self.url_database = {}
- def _encode(self, num):
- r = num % self.b
- encoded_string = self.base[r]
- q = int(num / self.b)
- while q > 0:
- r = q % self.b
- encoded_string = self.base[r] + encoded_string
- return encoded_string
- def _decode(self, n):
- decoded_string = 0
- for i in range(len(n)):
- decoded_string = decoded_string * self.b + self.base.index(n[i])
- return str(decoded_string)
- def post(self, url, content):
- protocol = url[:url.find('/') + 2]
- zone = url[url.find('.'):]
- encoded_string = self._encode(len(self.url_database))
- shorten_url = '{}{}{}'.format(protocol, len(self.url_database), zone)
- self.url_database.update({encoded_string: (shorten_url, content)})
- return shorten_url
- def get(self, url):
- n = url[url.find('/') + 2:url.find('.')]
- decoded_string = self._decode(n)
- if decoded_string in self.url_database:
- if self.url_database[decoded_string][0] != url:
- return 'error'
- else:
- return self.url_database[decoded_string][1]
- else:
- return 'error'
- n = int(input())
- u = URLShortener()
- for i in range(n):
- inp = input().split()
- req_type = inp[0]
- req_url = inp[1]
- if req_type == 'post':
- req_content = ' '.join(inp[2:])
- print(u.post(req_url, req_content))
- elif req_type == 'get':
- print(u.get(req_url))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement