 python3 factorial | Sololearn: Learn to code for FREE!

+4

# python3 factorial

fact = 1 test = int(input()) for i in range(test): n = int(input()) for z in range(1,n+1): fact = fact* z print(fact) why when i submit it to codechef i am getting wrong answer the conditions are n to be positive and less than 100

+3

Well, you tagged your question with the keyword recursion and there is no recursion here... Start by creating a function named factorial that take one integer.

+2

I Am Anushka You have not validated the input condition anywhere, so your code will fail their test case. Second thing, after calculating the factorial of one input, reset fact = 1 else fact will take last calculated value giving wrong results.

+2

To the downvoter, if you have guts explain the reson for downvoting !

+2

Use this function: def factorial(x): f = 1 for i in range(1, x + 1): f = f * i return f

+1

https://code.sololearn.com/cRGMhe7H98W8/?ref=app

+1

Well here the last value of fact is not deleted and is making errors

0

All was already explained. But I do encourage you to use the code provided by Drax . As you can tell, it looks cleaner and it's simpler. As a bonus to Drax code, you should learn about the lru_cache decorator, from Python Standard Library. It is very powerful for recursive functions such as this one. It would basically store in cache values of the factorial() function that were once calculated, and use them for other calculations. For example, after computing factorial(3) like in the Drax's example, computing factorial(4) would just result in 4 * factorial(3), and factorial(3) output is already stored in cache, so no need to compute it again. This leads to faster computing as the function is used. Happy coding! :)

0

you can use recursion like here https://code.sololearn.com/chgOI9Urg03b/?ref=app