python - 在 Python 3 中打印给定系列的谐波系列
解决方案
问题
我们要迭代n
(1, 2, 3, 4, 5, ...) 并将其传递到公式nx/n!
中,例如用户错误x
由这行代码定义x = int(input("What's the value of x? "))
,所以图像用户输入数字 5,所以我们需要得到:1*5/1!
, 2*5/2!
, 3*5/3!
, 4*5/4!
.
这是另一个问题:Python 的!
符号表示布尔反转,所以 !true 等于 false,而不是阶乘。
Python中的阶乘函数
所以我们需要定义函数阶乘:
def factorial(number):
fact = 1
for n in range(1, number+1):
fact *= n # The same as fact = fact * n
return fact
# TEST OF THE FACTORIAL FUNCTION
# print(f'factorial(3) == 1*2*3 => { factorial(3) == 1*2*3 }')
序列的限制
我们实际上需要nlim
从用户那里获取告诉循环何时停止的数字。
nlim = int(input("What's the limit of the sequence? "))
序列
因此,我们需要让 Python 评估这个(如果x
等于5
并且n
从1
一步1
增加到 limit nlim
):1*5/factorial(1)
,2*5/factorial(2)
,3*5/factorial(3)
等等。
results = [] # in this list all the results will be stored
for n in range(1, nlim+1):
results.append((n*x) / factorial(n)) # here comes the formula!
读取序列
for i, result in enumerate(results):
# enumerate([7, 8, 9]) will give us 2D list with indexes [[0, 7], [1, 8], [2, 9]]
# Then we will iterate this, so on each loop cycle we get [0, 7], then [1, 8] and so on
# if we do following: a, b = [1, 2] then variable a will be 1 and variable b will be 2
print(f'result[{ i }]: { result }')
所有代码
def factorial(number):
fact = 1
for n in range(1, number+1):
fact *= n
return fact
x = int(input("What's the value of x? "))
nlim = int(input("What's the limit of the sequence? "))
results = []
for n in range(1, nlim+1):
results.append((n*x) / factorial(n))
for i, result in enumerate(results):
print(f'result[{ i }]: { result }')
推荐阅读
- node.js - 运行执行 Powershell 脚本的节点应用程序可执行文件时出错
- python - 在 Numpy 或 Pandas 中分割 Linspace
- python - 将三通道图像转换为单通道图像
- python - 模型类在 Django 中被视为局部变量
- linux - 如何使用 --file=script-file 选项在 sed 命令中输入要搜索和替换的文件
- angular - angular 6 bootstrap 如何在组件模板中将宽度设置为 td 表
- python - Scraper 未提取 url 链接:
- c - 确定用户输入值的数据类型
- python - 从另一个类访问实例变量
- java - 如何从可执行文件加载我的本地主机 java spring boot web 应用程序