首页 > 解决方案 > 在 Python 3 中打印给定系列的谐波系列

问题描述

我想在 python 中打印谐波系列如下,但我不明白该怎么做,请帮忙,如果你能解释一下你是如何做到的,那就太好了。我没有尝试任何代码,也无法在网上找到它

在此处输入图像描述

标签: 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中的阶乘函数

所以我们需要定义函数阶乘:

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并且n1一步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 }')

推荐阅读