Python How to generate random integers with multiple ranges?

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

My code is:

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
+4
source share
5 answers

Not perfect

from random import randint, choice

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

As Blender said, a clearer version

from random import randint, choice

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

foor 3 , . .

+1

!

; , , .

:

, (0, 10), (20, 30) (40, 50); , , :

  • .
  • .

:

, (0, 2), (4, 6) (10, 100);

, . , , .

- , .

1:

, . , .

; . . 2.

2:

. . :

import random;
def randomPicker(howMany, *ranges):
    mergedRange = reduce(lambda a, b: a + b, ranges);
    ans = [];
    for i in range(howMany):
        ans.append(random.choice(mergedRange));
    return ans;

:

>>> randomPicker(5, range(0, 10), range(15, 20), range(40, 60));
[47, 50, 4, 50, 16]
>>> randomPicker(5, range(0, 10), range(70, 90), range(40, 60));
[0, 9, 55, 46, 44]
>>> randomPicker(5, range(0, 10), range(40, 60));
[50, 43, 7, 42, 4]
>>> 

randomPicker , .

, .

+1

:

from random import randint, choice

randoms = []
counter = 0    
while True:
   new_random = (choice([randint(1,5),randint(9,15),randint(21,27)]))
   if new_random not in randoms:
      randoms.append(new_random)
      counter += 1
   if counter == 5 :
      break
print randoms
0

, , , .

The main idea here is that you have a fixed number of options, so you can essentially have one range for the job, and then display the result in the desired ranges. Or if you want to look at it differently, create a function f(x) -> ythat comes down to the same thing.

from random import randint

for i in xrange(5):
    n = randint(1,19)
    if n > 12:
        print(n + 8)
    elif n > 5:
        print(n + 3)
    else:
        print(n)

Or using the function:

from random import randint

def plot_to_ranges(n):
    if n > 12:
        return n + 8
    elif n > 5:
        return n + 3
    else:
        return n

for i in xrange(5):
    n = randint(1,19)
    print(plot_to_ranges(n))

If you are using Python 3.x, you should change xrangeto range.

0
source

Source: https://habr.com/ru/post/1616019/


All Articles