split a list based on a predicate

  • Thread starter Rajanikanth Jammalamadaka
  • Start date
R

Rajanikanth Jammalamadaka

Hi!

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

Thanks,

Rajanikanth
 
B

bearophileHUGS

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
 
B

beginner

Hi,

Hi!

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

Thanks,

Rajanikanth

Here is an idea. It is not the most efficient code!

def combine(l, a):
if not l or l[-1]<a: l.append(a)
return l

reduce(combine, [0,1,2,3,0,1,2,2,3], [])

best regards,
beginner
 
R

Rajanikanth Jammalamadaka

Thanks for all of your replies.

Rajanikanth

Hi,

Hi!

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

Thanks,

Rajanikanth

Here is an idea. It is not the most efficient code!

def combine(l, a):
if not l or l[-1]<a: l.append(a)
return l

reduce(combine, [0,1,2,3,0,1,2,2,3], [])

best regards,
beginner
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top