Search code examples
pythonoptimizationfactorial

How can this code that does factorial to the user input be more optimized?


a=1
for _ in range(int(input("Enter: "))):
    a=a*(_+1); print(a)

This code does the factorial and prints the values as the process goes. An input of 5 would print: 1 2 6 24 120 It takes the past output value and multiplies the next number in input.

I want to get the same output or even better by only printing after the calculation is done. But the most important thing I want to achieve is a better optimized code that uses less lines. One more thing don't use libraries.


Solution

  • You could print only the final result, in a single line using max and a walrus assignment:

    print( max(1,a:=1,*(a := a*i for i in range(2,int(input("Enter: "))+1))) )
    

    This even works for 0! = 1

    If you want to print all the values in one line, you can write it without the max():

    print( a:=1, *(a := a*i for i in range(2,int(input("Enter: "))+1)) )