split a list based on a predicate

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Oct 8 20:14:03 EDT 2008


Rajanikanth Jammalamadaka:
> Is there a functional way to do this?
> I have an array [0,1,2,3,0,1,2,2,3] and I want the first chunk of
> non-decreasing values from this array (eg: In this case I want
> [0,1,2,3])

In Python sometimes the best way to write the code isn't functional,
this is readable code:

s = [3,1,2,3,0,1,2,2,3,3,2]

it = iter(s)
prec = it.next() #fix this if it can be empty
groups = [[prec]]
for x in it:
    if x < prec:
        groups.append([])
    groups[-1].append(x)
    prec = x
print groups

Output:
[[3], [1, 2, 3], [0, 1, 2, 2, 3, 3], [2]]

If you want more fancy code you may use something like this:

class Infinite:
    def __cmp__(self, other):
        return 0 if isinstance(other, Infinite) else 1
infinite = Infinite()

it = iter(s)
prec = infinite
groups = []
for x in it:
    if x < prec:
        groups.append([])
    groups[-1].append(x)
    prec = x
print groups

If you really want functional code you may try to use groupby().

bye,
bearophile



More information about the Python-list mailing list