![]() |
|
[Tut] 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python (/thread-99993.html) |
[Tut] 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python - xSicKxBot - 09-27-2022 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python 5/5 – (1 vote) Coding Challenge Challenge: Given an integer Code: dCode: dHere are three examples:
I’ll discuss three interesting methods to accomplish this easily in Python—my personal favorite is Method 2! Shortest Solution with randint() Let’s start with an easy hand-coded observation: The easiest way to create a random number with two digits is to use Code: randomCode: randint(10, 99)Code: randint(100,999)Code: randint(1000,9999)Here’s the same example in Python code: Code: from random import randint # Create random number with two digits (d=2):
print(randint(10, 99)) # Create random number with three digits (d=3):
print(randint(100, 999)) # Create random number with three digits (d=3):
print(randint(1000, 9999))This solution can be generalized by using the one-liner Code: random.randint(int('1'+'0'*(d-1)), int('9'*d))Code: dI used simple string arithmetic to define the start and end index of the random range:
Here’s the basic Python example: Code: import random def my_random(d): ''' Generates a random number with d digits ''' return random.randint(int('1'+'0'*(d-1)), int('9'*d)) for i in range(1, 10): print(my_random(i)) '''
Output:
8
82
296
5909
90957
227691
1348638
61368798
160959002 '''The cleanest solution is based on the Code: randrange()Code: randomUnlike Code: randint()Code: randrange()Code: dCode: random.randrange(10**(d-1), 10**d)Here’s an example: Code: import random def my_random(d): ''' Generates a random number with d digits ''' return random.randrange(10**(d-1), 10**d) for i in range(1, 10): print(my_random(i)) '''
Output:
7
64
872
2440
39255
979369
6897920
83589118
707920991 '''You can also use a one-liner to repeatedly execute the Code: random.randint()Code: string.join()Code: dCode: int(''.join(str(random.randint(0,9)) for _ in range(d)))Here’s this exact approach in a Python code snippet: Code: import random def my_random(d): ''' Generates a random number with d digits ''' return int(''.join(str(random.randint(0,9)) for _ in range(d))) for i in range(1, 10): print(my_random(i)) '''
Output:
6
92
135
156
95865
409722
349673
31144072
439469934 '''Thanks for reading through the whole article—I hope you got some value out of it. Here’s again a summary of how to best generate a random number with Code: d
Personally, I like Method 2 the most because it’s short, concise, and very efficient! |