Advertisement
jusohatam

Untitled

Sep 30th, 2020
756
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. class URLShortener:
  2.     def __init__(self):
  3.         self.base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4.         self.b = 62
  5.         self.url_database = {}
  6.  
  7.     def _encode(self, num):
  8.         r = num % self.b
  9.         encoded_string = self.base[r]
  10.         q = int(num / self.b)
  11.         while q > 0:
  12.             r = q % self.b
  13.             encoded_string = self.base[r] + encoded_string
  14.         return encoded_string
  15.  
  16.     def _decode(self, n):
  17.         decoded_string = 0
  18.         for i in range(len(n)):
  19.             decoded_string = decoded_string * self.b + self.base.index(n[i])
  20.         return str(decoded_string)
  21.  
  22.     def post(self, url, content):
  23.         protocol = url[:url.find('/') + 2]
  24.         zone = url[url.find('.'):]
  25.         encoded_string = self._encode(len(self.url_database))
  26.         shorten_url = '{}{}{}'.format(protocol, len(self.url_database), zone)
  27.         self.url_database.update({encoded_string: (shorten_url, content)})
  28.         return shorten_url
  29.  
  30.     def get(self, url):
  31.         n = url[url.find('/') + 2:url.find('.')]
  32.         decoded_string = self._decode(n)
  33.         if decoded_string in self.url_database:
  34.             if self.url_database[decoded_string][0] != url:
  35.                 return 'error'
  36.             else:
  37.                 return self.url_database[decoded_string][1]
  38.         else:
  39.             return 'error'
  40.  
  41.  
  42. n = int(input())
  43. u = URLShortener()
  44. for i in range(n):
  45.     inp = input().split()
  46.     req_type = inp[0]
  47.     req_url = inp[1]
  48.     if req_type == 'post':
  49.         req_content = ' '.join(inp[2:])
  50.         print(u.post(req_url, req_content))
  51.     elif req_type == 'get':
  52.         print(u.get(req_url))
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement