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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With