Python代码补全计划: DAY-2

声明:该系列文章首发于公众号:Y1X1n安全,转载请注明出处!本公众号所分享内容仅用于每一个爱好者之间的技术讨论,所有渗透及工具的使用都需获取授权,禁止用于违法途径,否则需自行承担,本公众号及作者不承担相应的后果。

Question 2

1、Question:

编写一个可以计算给定数字阶乘的程序。结果应在一行上以逗号分隔的顺序打印。假设向程序提供以下输入:8
然后,输出应该是:40320

数字阶乘是指将一个非负整数 n 的所有小于等于 n 的正整数相乘的结果,通常用符号 n! 表示。例如,5! = 5 x 4 x 3 x 2 x 1 = 120。


Hints:

1、如果向问题提供输入数据,则应将其假定为控制台输入。
2、0 的阶乘为 1
3、在 Python 2 中,使用 raw_input() 读取用户输入,而在 Python 3 中,应该使用 input() 函数。同时,Python 3 中的 print 语句需要使用括号来包围打印的内容,例如 print(fact(x))。


2、Solution

1、Python 2解法

def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

x = int(raw_input()) # 使用 int(raw_input()) 读取用户输入的数字
print fact(x)

# 利用递归的方式,将 x 的阶乘问题转化为 (x-1) 的阶乘问题。每次递归调用,都会使 x 减少 1,直到 x 减少到 0,然后递归停止,开始返回值。

2、 Python 3解法

  • Using While Loop

    n = int(input()) #input() function takes input as string type
                     #int() converts it to integer type
    fact = 1
    i = 1
    while i <= n:
        fact = fact * i;
        i = i + 1
    print(fact)
    
  • Using For Loop

    n = int(input()) #input() function takes input as string type
                    #int() converts it to integer type
    fact = 1
    for i in range(1,n+1):
        fact = fact * i
    print(fact)
    
  • Using Lambda Function

    n = int(input())
    def shortFact(x): return 1 if x <= 1 else x*shortFact(x-1)
    print(shortFact(n))
    

3、 Python 3解法

while True:
try:
    num = int(input("Enter a number: "))
    break
except ValueError as err:
    print(err)
# 使用try/except进行异常处理。程序假设用户输入的是一个整数。如果用户输入了一个非整数的字符串,程序将引发一个 ValueError 异常,并输出错误消息。
org = num
fact = 1
while num:
    fact = num * fact
    num = num - 1
print(f'the factorial of {org} is {fact}')
# 使用 f-字符串来将原始数字和阶乘值插入到输出字符串中。

4、 Python 3解法

from functools import reduce

def fun(acc, item):
	return acc*item

num = int(input())
print(reduce(fun,range(1, num+1), 1))

5、 Python 3解法 by: Y1X1n

def factorial(n, acc=1):
    if n == 0:
        return acc
    else:
        return factorial(n-1, n*acc)

if __name__ == '__main__':
    while True:
        n = int(input("输入数字:"))
        result = factorial(n)
        print(result)

# 使用一个额外的参数 acc 来跟踪阶乘的积。在每次递归调用时,它将当前数字 n 乘以 acc,并将结果传递给下一个递归调用。当 n 等于 0 时,阶乘的积被累加器 acc 返回。

时间复杂度为 O(n),因为它只需要执行 n 次递归调用。它的空间复杂度为 O(1),因为它只需要一个额外的参数来存储阶乘的积,没有使用列表或其他数据结构来存储中间结果。


📌 如果你对网络安全或编程感兴趣,可以搜索公众号“Y1X1n安全”,每天都会分享相关知识点,让我们一同加油!路漫漫其修远兮,吾将上下而求索。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值