0

kk is the number of lists present. l1 ,l2,l3 are the lists. In the following code, I have used 3 for loops to add elements in the 3 lists. Value of variable k could vary and so the lists. I want to know how do I use recursion to achieve this.

kk = 3  
l1 = [8,5,4]
l2 = [3,11,9]
l3 = [5,9,15,8]
maxi = []

for i in l1:
  for j in l2:
    for k in l3:
        maxi.append(i+j+k)
Kinjal Kachi
  • 111
  • 1
  • 1
  • 8
  • Related: https://stackoverflow.com/q/49059681/674039 – wim Jul 28 '18 at 15:59
  • I couldn't find a good duplicate. I imagine you will mostly get - `don't do that, use itertools` aswers. There is a recipe on activeState that might help [http://code.activestate.com/recipes/577415-recursive-function-to-replace-nested-for-loops-car/](http://code.activestate.com/recipes/577415-recursive-function-to-replace-nested-for-loops-car/) – wwii Jul 28 '18 at 16:32

1 Answers1

2

Sounds like you're looking for something along the lines of

[sum(t) for t in itertools.product(l1, l2, l3)]

which results in

[16, 20, 26, 19, 24, 28, 34, 27, 22, 26, 32, 25, 13, 17, 23, 16, 21, 25, 31, 24, 19, 23, 29,
 22, 12, 16, 22, 15, 20, 24, 30, 23, 18, 22, 28, 21]

Here itertools.product generates the Cartesian product of the input iterables. If you had some unknown number of iterables in a list you could do

iterables = [l1, l2, l3, ...]
[sum(t) for t in itertools.product(*iterables)]

to unpack them into arguments

A recursive solution would looks something like this. Warning: it is going to be worse in every way compared to the itertools solution.

def summations(*iterables, sums=()):
    if not iterables:
        return list(sums)
    head, *tail = iterables
    if not sums:
        return summations(*tail, sums=head)
    sums = (x+y for y in sums for x in head)
    return summations(*tail, sums=sums)

summations(l1, l2, 3)
# [16, 20, 26, 19, 24, 28, 34, 27, 22, 26, 32, 25, 13, 17, 23, 16, 21, 25, 31, 24, 19, 23, 29,
#  22, 12, 16, 22, 15, 20, 24, 30, 23, 18, 22, 28, 21]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96