number generator

Dick Moores rdm at rcblue.com
Tue Mar 13 20:53:41 EDT 2007


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!

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.)

Dick Moores




More information about the Python-list mailing list