Not sure why I am getting this error. The math seems to work for me on paper. Need help understanding what I am missing. The error...
Oops, try again. factorial(2) returned 3 instead of 2
My paper math says that the following steps would execute with this code:
total = 2
(range = 2, 1)
for 2 in range
if 2 is > than 1 (true so execute)
total = 2 * 2 - 1 (total = 2)
for 1 in range
if 1 is > than 1 (false so break)
return total which is 2
(I figured out what went wrong on this as I was typing this post. I needed the () around the i - 1 so that it calculated before being multiplied by total)
Figured I'd post it any ways to get feed back and hope that it helps someone else. Any suggestions on how to simplify this or make it cleaner? Not a fan of the way I did the range function, seems less than ideal. Any suggestions?
def factorial(x): total = x for i in range(x, 0, -1): if i > 1: total *= i - 1 return total