Reputation: 1012
I know how to add the numbers in a list recursively
def mysum(L):
if not L:
return 0
else:
return L[0] + mysum(L[1:])
Can you help me to build the subtraction recursively in the same manner(only one input - List).
mydiff([10,1,2,3])
Many thanks
Upvotes: 0
Views: 1178
Reputation: 9220
if the sequence is (3,2,1)
, the result is 0. But subtraction is going in reverse direction, i.e. 2 -1
than 3 - (2-1)
if you use return L[0] - mysum(L[1:])
.
So we have to use an accumulator which keeps the difference of first and second element of a sequence.
def mydiff(L, acc=None):
if not L:
return acc
else:
if acc is None:
acc = L[0] - L[1]
L = L[2:]
else:
acc -= L[0]
L = L[1:]
return mydiff(L, acc)
More simpler one;
def mysub(seq, acc=None):
seq = iter(seq)
if acc is None:
item = next(seq, None)
if item is None:
return acc
acc = item
item = next(seq, None)
if item is None:
return acc
return mysub(seq, acc - item)
Upvotes: 1
Reputation: 18917
The calculation to be done is
>>> 10-(1+(2+(3+0)))
4
so the first operation is a subtraction, but the rest of the operations remain additions. I think you need to use an inner function if you're not allowed to add a second parameter to the main function:
def mydiff(L):
def sub(L, first=False):
if not L:
return 0
else:
if first:
return L[0] - sub(L[1:])
else:
return L[0] + sub(L[1:])
return sub(L, True)
Testing:
>>> mydiff([10,1,2,3])
4
Upvotes: 1