Tuesday, September 17, 2024

Generate a Truly Random N digit number in Python

Copyable code at the bottom
















import time


RandomNoOfDigits = 2

print(f'Generate a random no of {RandomNoOfDigits} digits')

# use timestamp

ts = time.time()


# Convert timestamp into string

strTs = str(ts)


# split string using . and take part after decimal

strTs = strTs.split('.')

randomNo = strTs[1][-RandomNoOfDigits:]

print(f' 1 Random = {randomNo}')


''' If unit digit is 0, random no won't be of that many digits.

Ex: 03. So replacing unit digit 0 with 4 (my wish)

'''

if(int(randomNo[0]) == 0):

    randomNo = randomNo.replace('0','4')

    #randomNo[0]=4

    print(f' 11 Random = {randomNo}')


print(f' 2 Random = {randomNo}')


No comments:

Post a Comment

Please feel free to provide feedback, if any ..