SoFunction
Updated on 2024-10-30

Python Generate Short 8-bit Unique id Hands-on Tutorial

Test environment:

Win10

Python 3.5.4

Ideas for implementation

The use of 62 printable characters, by randomly generating 32-bit UUID, due to the UUID are hexadecimal, so the UUID is divided into 8 groups, each 4 for a group, and then through the mode 62 (characters 0-9, a-z, A-Z total number of 62 characters) operation, the results as an index to take out the characters, so that the rate of duplication is greatly reduced, the practice of testing, running 20000000 times, only appear 2 duplicate id (only tested once).

Of course, this is not up to the unique id, because there are still duplicates. The solution, you can consider combining the database, or other storage to achieve, in combination with the database as an example, we can create a new database table, and set an id field to the table, and set the primary key, or increase the unique constraints, each time you get 8 id, insert a data into the table, if you can successfully insert, that is not repeated, otherwise it is a duplicate id, and try again to get.

core code

#!/usr/bin/env python
# -*- coding:utf-8 -*- 
'''
@CreateTime: 2020/07/14 11:04
@Author : shouke
''' 
import uuid
array = [ "0", "1", "2", "3", "4", "5","6", "7", "8", "9",
     "a", "b", "c", "d", "e", "f","g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s","t", "u", "v", "w", "x", "y", "z",
     "A", "B", "C", "D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V","W", "X", "Y", "Z"
     ]
 
def get_short_id():
  id = str(uuid.uuid4()).replace("-", '') # Note that uuid4 is required here #
  buffer = []
  for i in range(0, 8):
    start = i * 4
    end = i * 4 + 4
    val = int(id[start:end], 16)
    (array[val % 62])
  return "".join(buffer)

test and verify

id_set = set() # Used to store generated unique ids
count = 0 # used to count the number of occurrences of repetition
index = [] # Record how many times the call to generate the 8-bit id appears to be duplicated
for i in range(0, 20000000):
  id = get_short_id()
  if id in id_set:
    count += 1
    (str(i+1))
  else:
    id_set.add(id)
  print('id:%s, run %s times, repeat count:%s , repeat rate:%s, repeat order %s' % (id, i+1, count, count/(i+1)*100, ','.join(index)))
 

ADDITIONAL: 10 randomly generated 8-digit school numbers starting with 2019 using python

import random means to introduce the built-in module random, and j stands for

The number of rows, range(), is a function that generates random numbers, i controls the

Number of lines per line, str() indicates the type of string to be converted into

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more. If there is any mistake or something that has not been fully considered, please do not hesitate to give me advice.