1
\$\begingroup\$

A factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 5 (denoted as 5!) is 1*2*3*4*5 = 120. The factorial of 0 is 1.

def recur_factorial(x):
 if x == 1:
 return 1
 else:
 return (x * recur_factorial(x - 1))
num = int(input("Enter number: "))
print("The factorial of", num, "is", recur_factorial(num))

So I would like to know whether I could make this program shorter and more efficient.

Also, I would like to know the advantages and disadvantages of recursion.

asked May 22, 2019 at 12:06
\$\endgroup\$
6
  • 1
    \$\begingroup\$ The factorial of 0 is 1. What does this code do for x==0? \$\endgroup\$ Commented May 22, 2019 at 12:42
  • \$\begingroup\$ @MaartenFabré - I have edited my code to include your question above. \$\endgroup\$ Commented May 22, 2019 at 12:45
  • 1
    \$\begingroup\$ Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see what you may and may not do after receiving answers . \$\endgroup\$ Commented May 22, 2019 at 12:47
  • 1
    \$\begingroup\$ Once a question has an answer, leave the code in it alone. If the original code wasn't complete, please learn something from this for your next question. \$\endgroup\$ Commented May 22, 2019 at 12:48
  • \$\begingroup\$ @MaartenFabré - if num == 0: print ("The factorial of 0 is 1") \$\endgroup\$ Commented May 22, 2019 at 12:48

1 Answer 1

3
\$\begingroup\$

Looking over your code, this is what I have for you:

  • Your function can be turned into a one-liner
  • You should use if __name__ == '__main__' to ensure you're not running this program externally.

Refactored Code:

def recur_factorial(x):
 return 1 if x == 1 else (x * recur_factorial(x - 1))
def main():
 num = int(input("Enter number: "))
 print("The factorial of", num, "is", recur_factorial(num))
if __name__ == '__main__':
 main()

You can read this StackOverflow question for more information about the advantages and disadvantages of recursion

answered May 22, 2019 at 12:22
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.