In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to achieve factorial in Python, which is very detailed and has certain reference value. Friends who are interested must finish it!
I believe everyone is no stranger to factorials. If you don't know the factorial, you can see here:
The factorial of a number:
For example, the factorial of 5
Recursive functions are generally recommended for most tutorials in python:
#! / usr/bin/python3 "" Python2,3 can both "def factorial (n): # body function if n = = 1: return 1 return n * factorial (NMub 1) res = input (" Please enter n: ") print (factorial (res))
But this is not only inconvenient to read, but also may cause stack overflow when n is very large.
Factorial (1000) Traceback (most recent call last): File "", line 1, in File "", line 4, in factorial [Previous line repeated 995 more times] File ", line 2, in factorialRecursionError: maximum recursion depth exceeded in comparison
So I prefer this:
#! / usr/bin/pythonli = [] def factorial (n): global li result = 1 for i in range (n): li.append (iTun1) for j in li: result = result * j return resultprint (factorial (int ("Please enter n:"))
By storing a single list, memory usage can be effectively reduced, and this call takes up only a few stacks and does not cause an overflow.
Or there are functions in the math module that can be used:
Import matha = input ("N:") fac = math.factorial (a) print (fac)
Or very simple for:
# Chinese variable name is legal! # Chinese variable name is legal! Number = input ("number:") a = 1for i in range (1, number + 1): a = a * iprint (a) above is all the content of this article "how to achieve factorial in Python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 248
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.