在python中优化阶乘函数 [英] Optimizing a factorial function in python

查看:96
本文介绍了在python中优化阶乘函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经使用拆包参数(* x)实现了此功能,但是我想使其显示结果返回它,并且我希望它很好 optimization (优化),意味着我仍然需要它成为两行函数

So i have achieved this function with unpacking parameter(*x), but i want to make it display the result not return it , and i want a good optimization meaning i still need it to be a two lines function

1.def fac(*x):
    2.return (fac(list(x)[0], list(x)[1] - 1)*list(x)[1]) if list(x)[1] > 0 else 1//here i need the one line to print the factorial

我尝试通过实现lambda来实现这一目标,但是我不知道如何传递* x参数

i tried achieving this by implementing lambda but i didn't know how to pass the *x parameter

推荐答案

您的阶乘lambda是正确的.我认为您想为列表[1,2,3]计算阶乘并输出结果,这是实现此目标的方法.

Your factorial lambda is correct. I take it that you would like to calculate the factorials for a list say [1, 2, 3] and output the results, this is how you can achieve this.

fact = lambda x: x*fact(x-1) if x > 0 else 1
print(*[fact(i) for i in [1, 2, 3]])

将输出:1、2、6

另一种选择,如果您使用的是python 3.8 ,则可以通过新的walrus运算符(:=)使用列表解析,这会比较棘手,但是会计算并输出所有n阶乘包含在内,同时仍适合您所需的两行.

Another option, if you have python 3.8 is to use a list comprehension with the new walrus operator (:=), this is a bit more tricky but will calculate and output all factorials up to n inclusive whilst still fitting in your required two lines.

fac, n = 1, 5
print(*[fac for i in range(1, n+1) if (fac := fac*i)])

将输出:1、2、6、24、120

Which will output: 1, 2, 6, 24, 120

这篇关于在python中优化阶乘函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆