-1

I have written this code:

rand_map, lst = [2, 2, 6, 6, 8, 11, 4], []

for i in range(len(rand_map)):

    num = rand_map[i]
    lst.append(num)

    for j in range(i+1, len(rand_map)):
        assembly = num + rand_map[j]
        num += rand_map[j]
        lst.append(assembly)
print(sorted(lst))

Which gives this output:

[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]

I've been trying to rewrite this code using list comprehensions, but I don't know how. I have tried multiple ways (standard and itertools) but I just can't get it right. I'll be very grateful for your help!

CDJB
  • 14,043
  • 5
  • 29
  • 55
777moneymaker
  • 697
  • 4
  • 15
  • 5
    If it looks too complex for a list comprehension it might actually be to complex for a list comprehension. – Klaus D. Jan 19 '20 at 22:53

1 Answers1

1

I came up with a couple of approaches for this problem:

Approach 1 - Vanilla list comprehension

In this approach, we iterate two variables, i and j and calculate the sum of the elements between these two indexes.

Code:

>>> rand_map = [2, 2, 6, 6, 8, 11, 4]
>>> sorted([sum(rand_map[i:i+j+1]) for i in range(len(rand_map)) for j in range(len(rand_map)-i)])
[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]

Approach 2 - Itertools

In this approach, we use the itertools recipe from here to iterate n-wise through the rand_map list, and calculate the sums accordingly. This works in approximately the same way as the first approach, but is a bit tider.

Code:

from itertools import islice

def n_wise(iterable, n):
    return zip(*(islice(iterable, i, None) for i in range(n)))

print(sorted([sum(x) for n in range(len(rand_map)) for x in n_wise(rand_map, n+1)]))

Output:

[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]
CDJB
  • 14,043
  • 5
  • 29
  • 55