How do I create a URL shortener?

后端 未结 30 2056
我寻月下人不归
我寻月下人不归 2020-11-22 05:11

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to \"http://www.example.org/abcdef\

30条回答
  •  别跟我提以往
    2020-11-22 05:37

    My Python 3 version

    base_list = list("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    base = len(base_list)
    
    def encode(num: int):
        result = []
        if num == 0:
            result.append(base_list[0])
    
        while num > 0:
            result.append(base_list[num % base])
            num //= base
    
        print("".join(reversed(result)))
    
    def decode(code: str):
        num = 0
        code_list = list(code)
        for index, code in enumerate(reversed(code_list)):
            num += base_list.index(code) * base ** index
        print(num)
    
    if __name__ == '__main__':
        encode(341413134141)
        decode("60FoItT")
    

提交回复
热议问题