This will be speedier and cleaner as it does not do conditioning in the actual recursion. It is still a function, albeit with another nested in.
def odd_factorial(x):
def do_fact(x):
if x == 3:
return 3
return x * do_fact(x - 2)
if x < 5:
raise ValueError("X must be at least 5")
if not x % 2:
x -= 1
return do_fact(x)
Running:
>>> odd_factorial(5)
15
>>> odd_factorial(6)
15
>>> odd_factorial(7)
105
>>> odd_factorial(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 9, in odd_factorial
raise ValueError("X must be at least 5")
ValueError: X must be at least 5
>>> odd_factorial(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 9, in odd_factorial
raise ValueError("X must be at least 5")
ValueError: X must be at least 5
Another way is to return 15
for odd_factorial(5)
and odd_factorial(6)
directly:
def odd_factorial(x):
if x < 5:
raise ValueError("x must be at least 5")
if x % 2 == 0:
x -= 1
if x == 5:
return 15
return x * odd_factorial(x - 2)