Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python

#1
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 d representing the number of digits. How to create a random number with d digits in Python?

Here are three examples:

  • my_random(2) generates 12
  • my_random(3) generates 389
  • my_random(10) generates 8943496710

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 random‘s randint(10, 99), with three digits is randint(100,999), and with four digits is randint(1000,9999).

Here’s the same example in Python 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 random.randint(int('1'+'0'*(d-1)), int('9'*d)) that generates the start and end values on the fly, based on the number of digits d.

I used simple string arithmetic to define the start and end index of the random range:

  • int('1'+'0'*(d-1)) creates the start index such as 100 for d=3.
  • int('9'*d)) creates the end index that’s included in randint() such as 999 for d=3.

Here’s the basic Python example:

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 '''

Cleanest Solution with randrange()


The cleanest solution is based on the randrange() function from the random module that takes the start and end index as input and generates a random number in between.

Unlike randint(), the end index is excluded in randrange(), so we have an easier way to construct our range for the d-digit random number problem: random.randrange(10**(d-1), 10**d).

Here’s an example:

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 '''

An Iterative Solution Aggregating Outputs of Single-Digit Random Function Calls


You can also use a one-liner to repeatedly execute the random.randint() function for each digit. To combine the digits, you convert each digit to a string, pass them into the string.join() function to get one string with d characters, and convert this string back to an integer:

int(''.join(str(random.randint(0,9)) for _ in range(d)))

Here’s this exact approach in a Python code snippet:

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 '''

Summary


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 d digits in Python:

  1. random.randint(int('1'+'0'*(d-1)), int('9'*d))
  2. random.randrange(10**(d-1), 10**d)
  3. int(''.join(str(random.randint(0,9)) for _ in range(d)))

Personally, I like Method 2 the most because it’s short, concise, and very efficient!




https://www.sickgaming.net/blog/2022/09/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] 5 Expert-Approved Ways to Remove Unicode Characters from a Python Dict xSicKxBot 0 16 Today, 04:51 AM
Last Post: xSicKxBot
  [Tut] [Fixed] Access Denied – OpenAI Error Reference Number 1020 xSicKxBot 0 1,419 08-10-2023, 09:24 PM
Last Post: xSicKxBot
  [Tut] [Fixed] Access Denied – OpenAI Error Reference Number 1020 xSicKxBot 0 1,390 05-25-2023, 04:45 PM
Last Post: xSicKxBot
  [Tut] F-String Python Hex, Oct, and Bin: Efficient Number Conversions xSicKxBot 0 1,671 03-28-2023, 12:01 PM
Last Post: xSicKxBot
  [Tut] [Fixed] Sendy Loading Lists Not Working (Loads Forever) xSicKxBot 0 1,207 02-14-2023, 08:12 PM
Last Post: xSicKxBot
  [Tut] Two Easy Ways to Encrypt and Decrypt Python Strings xSicKxBot 0 1,310 02-02-2023, 12:29 PM
Last Post: xSicKxBot
  [Tut] How I Generate Invoices For My Clients Using Python xSicKxBot 0 1,294 01-16-2023, 01:46 PM
Last Post: xSicKxBot
  [Tut] Python Generate HTML – 3 Easy Ways xSicKxBot 0 1,181 12-31-2022, 02:12 PM
Last Post: xSicKxBot
  [Tut] Python | Split String by Number xSicKxBot 0 1,152 12-05-2022, 01:21 PM
Last Post: xSicKxBot
  [Tut] (Fixed) ModuleNotFoundError: No Module Named ‘git’ | Python xSicKxBot 0 1,216 11-22-2022, 07:46 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016