Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a function to cover both single and multiple values

Say you have a value like this:

n = 5

and a function that returns the factorial of it, like so:

factorial(5)

How do you handle multiple values:

nums = [1,2,3,4,5]
factorial (nums)

so it returns the factorials of all these values as a list?

What's the cleanest way to handle this, without writing 2 methods? Does Python have a good way to handle these kinds of situations?

like image 336
Joan Venge Avatar asked Nov 26 '22 23:11

Joan Venge


1 Answers

def Factorial(arg):
    try:
        it = iter(arg)
    except TypeError:
        pass
    else:
        return [Factorial(x) for x in it]
    return math.factorial(arg)

If it's iterable, apply recursivly. Otherwise, proceed normally.

Alternatively, you could move the last return into the except block.

If you are sure the body of Factorial will never raise TypeError, it could be simplified to:

def Factorial(arg):
    try:
        return [Factorial(x) for x in arg]
    except TypeError:
        return math.factorial(arg)
like image 136
4 revs, 3 users 84% Avatar answered Dec 05 '22 04:12

4 revs, 3 users 84%