curdle a list

kevin parks kp87 at lycos.com
Thu Jul 19 22:27:13 EDT 2001


I've got a little function that takes a list and subdivides 
it randomly. so that i can say:

>>> x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
>>> clump.clump(x)

and it will return a list like any of the below lists:

[[1], [2, 3], [4], [5, 6, 7, 8, 9], [10, 11, 12], [13, 14], [15], 
[16, 17], [18], [19, 20, 21], [22], [23, 24]]
[[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11, 12], [13, 14], [15, 16], 
[17, 18, 19, 20], [21, 22], [23, 24]]
[[1], [2, 3, 4], [5, 6], [7, 8], [9, 10, 11, 12, 13, 14], [15, 16, 
17], [18], [19], [20, 21, 22], [23, 24]]
[[1, 2, 3, 4], [5, 6], [7, 8], [9], [10, 11, 12, 13], [14, 15, 16], 
[17, 18, 19, 20], [21, 22, 23, 24]]
[[1, 2], [3], [4, 5], [6, 7], [8], [9], [10, 11, 12, 13], [14, 15, 
16, 17, 18, 19, 20], [21, 22], [23, 24]]

So, now what i'd like to do is make a function that would be like:

curdle(seq, prob)

where prob is the probability that there will be a partition between
any two elements.
So that should be something like:

import random

def curdle(seq, Prob):
        if not seq:
                return []
        result = [seq[:1]]
        for e in seq[1:]:
                # either extend last clump or start a new one,
depending on Prob
                if random.random() < Prob:
                        # extend last lump
                        result[-1].append(e)
                else:
                        # start a new lump
                        result.append([e])
        return result
        
But, i am not 100% sure i am getting the right results. It seems as
though
i am, but i was hoping that if it was off someone with knowledge of
testing
randomness would give it the once over. Prob set to 0.5 should
give me 50% chance of a new subsequence. 0.0 should give me
subdivisions
all the time and 1.0 should give me the flat list back (or rather on
big list
nested as an element inside the list.

cheers,

kevin parks
Seoul, Korea

kp87 at lycos.com



More information about the Python-list mailing list