number generator

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Mar 14 02:14:49 CET 2007


On Tue, 13 Mar 2007 17:53:41 -0700, Dick Moores wrote:

> At 05:47 PM 3/10/2007, Paul Rubin wrote:
> 
>>The fencepost method still seems to be simplest:
>>
>>     t = sorted(random.sample(xrange(1,50), 4))
>>     print [(j-i) for i,j in zip([0]+t, t+[50])]
> 
> =================================
> M = 50
> N = 4
> def sumRndIntRubin(M, N):
>      import random
>      t = sorted(random.sample(xrange(1,M), N-1))
>      lst = [(j-i) for i,j in zip([0]+t, t+[M])]
> 
>      print t
>      print t + [M]
>      print [0] + t
>      print lst
>      print sum(lst)
> 
> sumRndIntRubin(M, N)
> ====================================
> [6, 20, 31]
> [6, 20, 31, 50]
> [0, 6, 20, 31]
> [6, 14, 11, 19]
> 50
> 
> I understand what zip() and random.sample() are doing, and the above 
> helps me get inside the fencepost method, but I don't understand WHY 
> it works, or how in the world anyone could have devised it. It is 
> truly magical to me!

Me too. Although Alex Martelli's algorithm:

map([random.randrange(5) for i in xrange(45)].count, xrange(5))

(each value needs adjusting up by one) really boggles my brain. I'm going
to have to think about that.


> BTW I did see this in this thread, "Suppose you have a fixed 
> telegraph pole at N and a fixed telegraph pole at M, and you're given 
> 5 more telegraph poles..." (Gerard Flanagan), but even now I can't 
> take it anywhere. I guess I'm just a dim bulb. (I thought I was a 
> fairly smart guy until I took up Python.)

Consider the distance between each paid of consecutive poles. The sum of
the distances must add up to the distance from the first to the last, and
if there are two fixed poles plus five in between, there are five
distances.

Hence five (random) distances which sum to the required total.



-- 
Steven D'Aprano 




More information about the Python-list mailing list