【问题标题】:python symbol for consecutive numbers [duplicate]连续数字的python符号[重复]
【发布时间】:2019-02-05 19:25:03
【问题描述】:

我偶然发现了一个需要使用“未知公式”的问题。

此处引用:http://www.murderousmaths.co.uk/books/unknownform.htm

我从高处到低处都没有找到与“!”等效的python符号以作者使用它的方式。

# Example of authors use of '!'
5! == 5x4x3x2x1

我知道我可以使用循环来创建它,就像在这篇文章中一样:Sum consecutive numbers in a list. Python

但我希望借此机会学习。


编辑

有一个关于阶乘的好帖子 (Function for Factorial in Python),但我更喜欢下面提供的解决方案答案。非常清晰简洁。

【问题讨论】:

标签: python formula


【解决方案1】:

这是一个称为factorial 的数学函数,在another question 中有详细介绍。

最简单的方法是:

import math
math.factorial(5)

函数式方法:

from functools import reduce
import operator
answer = reduce(operator.mul, range(1, 6))

循环方法:

answer = 1
for i in range(5):
    answer *= i+1

Another answer uses a list comprehension.

【讨论】:

  • 太棒了!这正是我一直在寻找的。谢谢!
  • 如果你要使用functools,至少使用operator.mul... :)
  • 或者用 numpy:import numpy as np; def factorial(n): return np.product(np.array(range(1, n + 1)))
  • @Tomothy32 我根据你的建议编辑了答案
猜你喜欢
  • 2019-01-12
  • 2019-11-23
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多