Search code examples
pythonfunctionoptimizationfactorial

Optimizing a factorial function in python


So i have achieved this function with unpacking parameter(*x), but i want to make it display the result not return it , and i want a good optimization meaning i still need it to be a two lines function

1.def fac(*x):
    2.return (fac(list(x)[0], list(x)[1] - 1)*list(x)[1]) if list(x)[1] > 0 else 1//here i need the one line to print the factorial

i tried achieving this by implementing lambda but i didn't know how to pass the *x parameter


Solution

  • Your factorial lambda is correct. I take it that you would like to calculate the factorials for a list say [1, 2, 3] and output the results, this is how you can achieve this.

    fact = lambda x: x*fact(x-1) if x > 0 else 1
    print(*[fact(i) for i in [1, 2, 3]])
    

    Which will output: 1, 2, 6

    Another option, if you have python 3.8 is to use a list comprehension with the new walrus operator (:=), this is a bit more tricky but will calculate and output all factorials up to n inclusive whilst still fitting in your required two lines.

    fac, n = 1, 5
    print(*[fac for i in range(1, n+1) if (fac := fac*i)])
    

    Which will output: 1, 2, 6, 24, 120