0

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
2
  • 1
    It sums all the items in the items array Commented Jul 30, 2019 at 7:08
  • @Toshith could be please give an example for items? I am afraid the line "head, tail=items" is syntactically wrong according to python, as it will raise a "ValueError: too many values to unpack" Commented Jul 30, 2019 at 7:12

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.