+ 2

Why this code is showing error can you explain?

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

15th Apr 2020, 10:03 AM
Payal Sharma
Payal Sharma - avatar
11 odpowiedzi
+ 4
Payal Sharma , you didn't declare the base case in the recursion, so the function is called infinitely. Look at the correct code. https://code.sololearn.com/cg17G7G9yY1F/?ref=app
15th Apr 2020, 10:07 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
You need stop condition in recursive method Like if x==1: return 1
15th Apr 2020, 10:06 AM
Stephan
Stephan - avatar
+ 1
You have written the code in such a way that the recursion keeps going deeper until it runs out of depth, (processing power, time, etc) You could do this to get a result def factorial(x): return x * (x-1) print(factorial(5)) But I don't think this was your objective. The main problem was there was no way to stop the recursive loop
15th Apr 2020, 10:16 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Justus , in fact it's needed, because 0! = 1. If you call the function with 0 as argument, again it will run infinitely and will not calculate this specific case.
15th Apr 2020, 11:11 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
TheWh¡teCat 🇧🇬 the first condition was ok (if x==1) to exit the loop. x==0 isn't required
15th Apr 2020, 11:07 AM
Justus
Justus - avatar
0
TheWh¡teCat 🇧🇬 oh. I didn't check that
15th Apr 2020, 12:36 PM
Justus
Justus - avatar
0
def factorial(x): if x == 1: return x else: return x*factorial(x-1) print(factorial(5))
16th Apr 2020, 5:01 AM
Lajul Soni
Lajul Soni - avatar
0
you just missed one condition
16th Apr 2020, 5:01 AM
Lajul Soni
Lajul Soni - avatar
0
you are missing the base condition of the recursive method if x==1: return 1
16th Apr 2020, 4:03 PM
petenera_
petenera_ - avatar
- 1
Just type like this : def factorial(x): return x*x-1 print(factorial(5))
17th Apr 2020, 1:18 AM
Omar Khalil Bakhsh
Omar Khalil Bakhsh - avatar