如何根據 python 中的輸入數字生成唯一的 16 位字母數字。如果我們多次運行該函式,結果應該是相同的。例如,如果輸入是 100,程式回傳 12345678abcdefgh,下次如果用戶提供相同的輸入,它應該回傳相同的結果 12345678abcdefgh。
uj5u.com熱心網友回復:
您可以使用 hashlib 模塊對輸入整數進行哈希處理。如果輸入相同,生成的哈希將始終相同。
import hashlib
print('Enter a number to hash: ')
to_hash = input()
digest_32 = hashlib.md5(bytes(int(to_hash))).hexdigest()
digest_16 = digest_32[0:16]
# output: 6d0bb00954ceb7fbee436bb55a8397a9
print(digest_32)
# output: 6d0bb00954ceb7fb
print(digest_16)
uj5u.com熱心網友回復:
"""
generate unique 16 digit alphanumeric based on input number in python. Result
should be the same if we run the function multiple times. for example if
the input is 100 and the program returns 12345678abcdefgh and next time if the
user provides same input it should return the same result 12345678abcdefgh.
"""
# Note: This does not use hashlib because hash returns HEX values which
# are 16 alphanumeric characters:
# 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
def generate_alphanumeric(number):
# Convert the number to binary representation
binary = bin(number)
# remove 0b from binary representation prefix
mask_right_side = binary[2:]
# Create a mask to select 16 characters based on the binary representation.
# Creating padding 0's for the mask_left_side
mask_left_side = '0' * (16 - len(mask_right_side)) # Padding characters
# Create the 16 character mask
mask = mask_left_side mask_right_side
# Create a list of tuples of (zero_code, one_code)
zeros_codes = '12345678apqdexgh'
ones_codes = '90ijklmnobcrsfyz'
codes = list(zip(zeros_codes, ones_codes))
# Create the alphanumeric output.
if len(mask) <= 16:
result = ''
for index in range(16):
value = int(mask[index])
zero_code, one_code = codes[index]
if value: # mask value is 1
result = one_code
else:
result = zero_code
return result
else:
message = f'The entered values {number:,d} is greater that 65,' \
f'535. This is not allowed because the returned 16 ' \
f'character alphanumberic text will be a repeat of text ' \
f'assigned in the range of 0 to 65,535. This violates the ' \
f'requirement for unique text per number.'
return message
# Testing
print(generate_alphanumeric(100))
print(generate_alphanumeric(15))
print(generate_alphanumeric(0))
print(generate_alphanumeric(65_535))
print(generate_alphanumeric(65_536))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462186.html
