Reputation: 1
I am finding it difficult to interpret what the below code is trying to do . It is about the recursive algorithm . Especially the: if tail else head statement.
Assuming a list is defined and split into head and tail components
items=[1,10,7,4,5,9]
head,*tail=items
def sum(items):
head,tail=items
return head+sum(tail) if tail else head
Upvotes: 0
Views: 61
Reputation:
Answering your doubt on the statement "Especially the: if tail else head statement."
The above-said statement can also be written as
if(tail != None):
return head+sum(tail)
else:
return head
which makes a lot of sense on the first look.
Hope this helps you,
Reply on any query on the above
Upvotes: 2
Reputation: 2098
As long as the tail is not None type, the recursion will be there. If the tail is None, the recursion will terminate and head will be output and it will go up the chain.
This is my quick understanding. Other members have also given very good answers.
Upvotes: 0