Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update list recursively

Tags:

python

I have a list of dicts:

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]

I want to update the value of each element in this list by the sum of all remainders. (so 'one' will get the value 2+3+4+5) .

so that it will look like this:

a = [{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}]

'five' is the last, so it will not update .

Im not sure how to achieve this. Im thinking that you construct a function that will call itself recursivly something like:

def recursive(a):
   if len(a) == 1:
      return list(a[0].values())[0]
    else:
      val = list(a[0].values())[0]
      return val + recursive(a.pop(0))

But Im not sure to do this list(a[0].values())[0] is the "best" way. And this is also getting a KeyError: 0.

Any ideas?

like image 588
mrfr Avatar asked Feb 20 '19 21:02

mrfr


3 Answers

Iterative and in place solution

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]
sum_so_far = 0
first_flag = False
for i in a[::-1]:
    k,v = i.items()[0]   #For Python 3 k,v = list(i.items())[0]
    sum_so_far += v
    if first_flag:
        i[k] = sum_so_far # do not change the value at first

    first_flag=True

Output

[{'one': 15}, {'two': 14}, {'three': 12}, {'four': 9}, {'five': 5}]
like image 144
mad_ Avatar answered Nov 15 '22 17:11

mad_


Your problem comes from the output of a.pop(0). A.pop(0) returns the element at 0, not the list without the element at 0. Therefore, when you call recursively, you are indexing on a dict, rather than a list. What do you expect to be inputting into the recursive call?

I would guess you are trying to remove the 0th index, then call recursively. To do this,

a.pop(0);
return val + recursive(a)

edit: a note - key error 0 means you are indexing a dict with key 0 when key 0 does not yet exist.

like image 40
David Kaftan Avatar answered Nov 15 '22 16:11

David Kaftan


A possible recursive solution:

d = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]
def sums(data, _sum = 0):
  a, *b = data
  if not b:
    return [a], list(a.values())[0]
  c, _d = sums(b, _sum+list(a.values())[0])
  return [{list(a.keys())[0]:_d}, *c], _d+list(a.values())[0]

result, _ = sums(d)

Output:

[{'one': 14}, {'two': 12}, {'three': 9}, {'four': 5}, {'five': 5}]
like image 36
Ajax1234 Avatar answered Nov 15 '22 17:11

Ajax1234