问题描述
我想按如下方式在python中打印谐波系列,但我不明白该怎么做,请帮忙,如果您能解释一下您是如何做到的,那就太好了。我没有尝试过任何代码,也无法在网上找到它
解决方法
问题
我们想迭代 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 中的阶乘函数
所以我们需要定义函数 factorial:
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
增加到限制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,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 }')