garlfd
garlfd

Reputation: 149

How do I convert this into a comprehension? (Python)

This function produces the sum of the first n values, the sum of the second n values...etc.

Here is the function:

def collect_sum(iterable,n):
    for e in range(1,len(ite)+1):
        if e%n==0:
            yield sum(iterable[e-n:e])

for i in c_sum(range(1,21),5):
       print(i,end=' ')

This is supposed to return 15, 40, 65. When I use a list comprehension, it returns 0, 30, 40.

Upvotes: 0

Views: 87

Answers (3)

HennyH
HennyH

Reputation: 7944

def collect_sum(i,n):
    return (sum(g) for (_,g ) in groupby(i,key=lambda _,c=count():floor(next(c)/n)))
for v in collect_sum(range(1,21),5):
    print(v)

Produces:

15
40
65
90
>>> 

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Using itertools.islice:

   

In [28]: n=5

In [29]: from itertools import islice

In [30]: lis=range(1,21)

In [31]: it=iter(lis)

In [33]: [sum(islice(it,n))  for _ in xrange(len(lis)/n) ]

Out[33]: [15, 40, 65, 90]

Upvotes: 0

wim
wim

Reputation: 362587

# generator version
def collect_sum(iterable,n):
  for e in range(1,len(iterable)+1):
    if e%n==0:
      yield sum(iterable[e-n:e])

# list comprehension version
def collect_sum(iterable,n):
  return [sum(iterable[e-n:e]) for e in range(1,len(iterable)+1) if e%n==0] 

for i in collect_sum(range(1,21),5):
  print(i,end=' ')

Upvotes: 1

Related Questions