程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python implementation of simple short chain shorturl

編輯:Python

Realization principle

Put... In the database Short chain and long chain are mapped ; Table field id( Self increasing ), longurl, shorturl;
Use 0-9a-zA-Z Combine into five digits (62^5) Or six (62^6) Character to represent the field id ; Short chain and id Transform each other , Mapping and uniqueness can be achieved by using radix ;

python Code implementation

from random import shuffle
secret = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# secret = 'YTiqlfv682MtKzV0RjLgpWJwmXAbcNkIoyPZda9ExO3S7FBnGU15eHshDuQCr4'
# String obfuscation 
def random_string(s):
s = list(s)
shuffle(s)
print("".join(s))
return "".join(s)
# Decimal to 62 Base number 
def encode62(id):
num_list = []
while (id > 0):
remainder = id % 62
num_list.insert(0, secret[remainder])
id = id // 62
return "".join(num_list).rjust(6, secret[0])
# 62 Convert base to decimal 
def decode62(secret_str):
num_list = list(map(secret.index, secret_str))
num_sum = 0
for i, num in enumerate(num_list[::-1]):
num_sum += num * 62**i
return num_sum
print(encode62(138))
print(decode62(encode62(138)))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved