{"id":128382,"date":"2022-09-26T16:06:40","date_gmt":"2022-09-26T16:06:40","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=720085"},"modified":"2022-09-26T16:06:40","modified_gmt":"2022-09-26T16:06:40","slug":"3-best-ways-to-generate-a-random-number-with-a-fixed-amount-of-digits-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/09\/26\/3-best-ways-to-generate-a-random-number-with-a-fixed-amount-of-digits-in-python\/","title":{"rendered":"3 Best Ways to Generate a Random Number with a Fixed Amount of Digits in Python"},"content":{"rendered":"\n<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;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2>Coding Challenge<\/h2>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/2694.png\" alt=\"\u2694\" 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>\n<p>Here are three examples:<\/p>\n<ul>\n<li><code>my_random(2)<\/code> generates <code>12<\/code><\/li>\n<li><code>my_random(3)<\/code> generates <code>389<\/code><\/li>\n<li><code>my_random(10)<\/code> generates <code>8943496710<\/code><\/li>\n<\/ul>\n<p>I&#8217;ll discuss three interesting methods to accomplish this easily in Python&#8212;my personal favorite is <strong>Method 2<\/strong>!<\/p>\n<h2>Shortest Solution with randint()<\/h2>\n<p>Let&#8217;s start with an easy hand-coded observation:<\/p>\n<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>&#8216;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>\n<p>Here&#8217;s the same example in Python code:<\/p>\n<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):\nprint(randint(10, 99)) # Create random number with three digits (d=3):\nprint(randint(100, 999)) # Create random number with three digits (d=3):\nprint(randint(1000, 9999))<\/pre>\n<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>\n<p>I used simple string arithmetic to define the start and end index of the random range:<\/p>\n<ul>\n<li><code>int('1'+'0'*(d-1))<\/code> creates the start index such as 100 for <code>d=3<\/code>.<\/li>\n<li><code>int('9'*d))<\/code> creates the end index that&#8217;s included in <code>randint()<\/code> such as <code>999<\/code> for <code>d=3<\/code>.<\/li>\n<\/ul>\n<p>Here&#8217;s the basic Python example:<\/p>\n<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)) '''\nOutput:\n8\n82\n296\n5909\n90957\n227691\n1348638\n61368798\n160959002 '''<\/pre>\n<h2>Cleanest Solution with randrange()<\/h2>\n<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>\n<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>\n<p>Here&#8217;s an example:<\/p>\n<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)) '''\nOutput:\n7\n64\n872\n2440\n39255\n979369\n6897920\n83589118\n707920991 '''<\/pre>\n<h2>An Iterative Solution Aggregating Outputs of Single-Digit Random Function Calls<\/h2>\n<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>\n<p><code>int(''.join(str(random.randint(0,9)) for _ in range(d)))<\/code><\/p>\n<p>Here&#8217;s this exact approach in a Python code snippet:<\/p>\n<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)) '''\nOutput:\n6\n92\n135\n156\n95865\n409722\n349673\n31144072\n439469934 '''<\/pre>\n<h2>Summary<\/h2>\n<p>Thanks for reading through the whole article&#8212;I hope you got some value out of it. <\/p>\n<p>Here&#8217;s again a summary of how to best generate a random number with <code>d<\/code> digits in Python:<\/p>\n<ol class=\"has-global-color-8-background-color has-background\">\n<li><code>random.randint(int('1'+'0'*(d-1)), int('9'*d))<\/code><\/li>\n<li><code>random.randrange(10**(d-1), 10**d)<\/code><\/li>\n<li><code>int(''.join(str(random.randint(0,9)) for _ in range(d)))<\/code><\/li>\n<\/ol>\n<p>Personally, I like Method 2 the most because it&#8217;s short, concise, and very efficient!<\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (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&#8217;ll discuss three interesting methods to accomplish this easily in Python&#8212;my personal favorite is Method [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-128382","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128382","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=128382"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128382\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=128382"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=128382"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=128382"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}