Sick Gaming
[Tut] 3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.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

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;720085&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2>Coding Challenge</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2694.png" alt="⚔" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Challenge</strong>: Given an integer <code>d</code> representing the number of digits. How to create a random number with <code>d</code> digits in Python?</p>
<p>Here are three examples:</p>
<ul>
<li><code>my_random(2)</code> generates <code>12</code></li>
<li><code>my_random(3)</code> generates <code>389</code></li>
<li><code>my_random(10)</code> generates <code>8943496710</code></li>
</ul>
<p>I’ll discuss three interesting methods to accomplish this easily in Python—my personal favorite is <strong>Method 2</strong>!</p>
<h2>Shortest Solution with randint()</h2>
<p>Let’s start with an easy hand-coded observation:</p>
<p class="has-global-color-8-background-color has-background">The easiest way to create a random number with two digits is to use <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-random-module/" data-type="post" data-id="5030" target="_blank">random</a></code>‘s <code>randint(10, 99)</code>, with three digits is <code>randint(100,999)</code>, and with four digits is <code>randint(1000,9999)</code>. </p>
<p>Here’s the same example in Python code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p class="has-global-color-8-background-color has-background">This solution can be generalized by using the one-liner <code>random.randint(int('1'+'0'*(d-1)), int('9'*d))</code> that generates the start and end values on the fly, based on the number of digits <code>d</code>.</p>
<p>I used simple string arithmetic to define the start and end index of the random range:</p>
<ul>
<li><code>int('1'+'0'*(d-1))</code> creates the start index such as 100 for <code>d=3</code>.</li>
<li><code>int('9'*d))</code> creates the end index that’s included in <code>randint()</code> such as <code>999</code> for <code>d=3</code>.</li>
</ul>
<p>Here’s the basic Python example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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 '''</pre>
<h2>Cleanest Solution with randrange()</h2>
<p class="has-global-color-8-background-color has-background">The cleanest solution is based on the <code>randrange()</code> function from the <code>random</code> module that takes the start and end index as input and generates a random number in between. </p>
<p class="has-global-color-8-background-color has-background">Unlike <code>randint()</code>, the end index is <em>excluded </em>in <code>randrange()</code>, so we have an easier way to construct our range for the <code>d</code>-digit random number problem: <code>random.randrange(10**(d-1), 10**d)</code>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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 '''</pre>
<h2>An Iterative Solution Aggregating Outputs of Single-Digit Random Function Calls</h2>
<p class="has-global-color-8-background-color has-background">You can also use a one-liner to repeatedly execute the <code>random.randint()</code> function for each digit. To combine the digits, you <a href="https://blog.finxter.com/python-str-function/" data-type="post" data-id="23735" target="_blank" rel="noreferrer noopener">convert</a> each digit to a string, pass them into the <code><a href="https://blog.finxter.com/python-string-join/" data-type="post" data-id="26062" target="_blank" rel="noreferrer noopener">string.join()</a></code> function to get one string with <code>d</code> characters, and <a href="https://blog.finxter.com/python-int-function/" data-type="post" data-id="22715" target="_blank" rel="noreferrer noopener">convert</a> this string back to an integer:</p>
<p><code>int(''.join(str(random.randint(0,9)) for _ in range(d)))</code></p>
<p>Here’s this exact approach in a Python code snippet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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 '''</pre>
<h2>Summary</h2>
<p>Thanks for reading through the whole article—I hope you got some value out of it. </p>
<p>Here’s again a summary of how to best generate a random number with <code>d</code> digits in Python:</p>
<ol class="has-global-color-8-background-color has-background">
<li><code>random.randint(int('1'+'0'*(d-1)), int('9'*d))</code></li>
<li><code>random.randrange(10**(d-1), 10**d)</code></li>
<li><code>int(''.join(str(random.randint(0,9)) for _ in range(d)))</code></li>
</ol>
<p>Personally, I like Method 2 the most because it’s short, concise, and very efficient!</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
</div>


https://www.sickgaming.net/blog/2022/09/26/3-best-ways-to-generate-a-random-number-with-a-fixed-amount-of-digits-in-python/