Question #103970

def mystery(l,v):

if len(l) == 0:

return (v)

else:

return (mystery(l[:-1],l[-1]+v))

What does mystery([22,14,19,65,82,55],1) return?

Expert's answer

program code:


def mystery(l,v):

  if len(l) == 0:

    return (v)

  else:

    return (mystery(l[:-1],l[-1]+v))

   

print(mystery([22,14,19,65,82,55],1))

__________________________________


The mystery (l, v) function is recursive.

 Adds the last item to the list and removes it from the list.

The function works until the list is empty.

The function returns a value equal to the sum of:

1+55+82+65+19+14+22 = 258



Step by step function execution:

[22, 14, 19, 65, 82, 55] 1 (The initial value of the amount is set to 1)

[22, 14, 19, 65, 82] 56

[22, 14, 19, 65] 138

[22, 14, 19] 203

[22, 14] 222

[22] 236

[ ] 258 (The list is empty).

----------------------------------------------------------------------


The function will return the number 258.

LATEST TUTORIALS
APPROVED BY CLIENTS