Expand a random range from 1–5 to 1–7

前端 未结 30 3298
一个人的身影
一个人的身影 2020-11-22 07:29

Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.

  1. What is a simple so
30条回答
  •  借酒劲吻你
    2020-11-22 08:24

    Assuming that rand(n) here means "random integer in a uniform distribution from 0 to n-1", here's a code sample using Python's randint, which has that effect. It uses only randint(5), and constants, to produce the effect of randint(7). A little silly, actually

    from random import randint
    sum = 7
    while sum >= 7:
        first = randint(0,5)   
        toadd = 9999
        while toadd>1:
            toadd = randint(0,5)
        if toadd:
            sum = first+5
        else:
            sum = first
    
    assert 7>sum>=0 
    print sum
    

提交回复
热议问题