Python- How to generate random integers with multiple ranges?

后端 未结 6 2013
忘掉有多难
忘掉有多难 2021-01-12 01:25

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), (

6条回答
  •  温柔的废话
    2021-01-12 01:42

    There are some interesting answers here, though I think this problem can be solved with a bit less code, even if it is a little bit less readable.

    The basic idea here is that you have a fixed number of choices so you can essentially have one range to do the job and then plot the result to the ranges you want. Or if you want to consider it another way, create a function f(x) -> y that boils 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, with a 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're using Python 3.x, you should change xrange to range.

提交回复
热议问题