I write a function that calculate sum of all elements in a list with recursion + ternary

During my programming coursework, I learned about recursive function. It took me while how it works, but now I think I understand the basic concept behind it.

So to practice it, I write this code. It calculates sum of all elements in a list. Originally, it look like this:

def sum_of_set(h):
    if len(h) == 0:
        return 0

    return sum_of_set(h[1:]) + h[0]

Then, with ternary, i rewrite it.

def sum_of_set(h):
    return 0 if len(h) == 0 else sum_of_set(h[1:]) + h[0]

What do you think? Well aside from the programming concept, is it a good code from (any) good principle and practice? I wanted to know when to use recursion and when to use if…else/ternary.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.