PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to generate random integers with multiple ranges?

 July 21, 2022     integer, python, random     No comments   

Issue

I've run into confusion in generating X amount of random integers from different sets of (a,b). For example, I would like to generate 5 random integers coming from (1,5), (9,15),and (21,27). My code generates 5 random integers but only between 21 and 27 and not from the other two. Ideally I'd like to see something like 1,4,13,22,25 instead of 21,21,25,24,27.

My code:

from random import randint
n = 0
while n < 5:
    n += 1
    for i in (randint(1,5),randint(9,15),randint(21,27)):
        x = i
    print i

Solution

Not ideal but it works.

First it gets random numbers from all ranges and next it selects (randomly) one value.

from random import randint, choice

for _ in range(5):
    print(choice([randint(1,5),randint(9,15),randint(21,27)]))

As Blender said - cleaner version - first it selects (randomly) one range and later it gets random value from this range.

from random import randint, choice

for _ in range(5):
    r = choice([(1,5),(9,15),(21,27)])
    print(randint(*r))


Answered By - furas
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing