python 中用户输入的计算方法

calculating means with input from a user in python

我正在尝试创建一个函数来计算用户给我的数字的算术平均值、几何平均值和谐波平均值。结果应该是这样的:对于数字 4 和 9 数字的算术平均值为 6.5 数字的几何平均数是 6 数字的调和平均值为 5.538461538461538

这是我的代码:

  import math
  def fancy_mean():
      number=input("Please enter the numbers, one in each line: ")
      total_arithmetic=0
      multiplication_result_geometric=1
      harmonical_total=0
      count_of_numbers=0
      list_of_numbers=[]
      while  number!="":
          number=float(number)
          list_of_numbers.append(number)
          count_of_numbers+=1
          for i in list_of_numbers:
              total_arithmetic=total_arithmetic+i
              arithmatic_mean=float(total_arithmetic/count_of_numbers)
              multiplication_result_geometric=multiplication_result_geometric*i
              geomatric_mean=float(math.sqrt(multiplication_result_geometric))
              harmonical_total=harmonical_total+(1/i)
             harmonical_mean=float(count_of_numbers/harmonical_total)

      number=input("Please enter the numbers, one in each line: ")
    if not list_of_numbers:
      return
print("The arithmetic mean of the numbers is",arithmatic_mean)
print("The geometric mean of the numbers is",geomatric_mean)
print("The harmonic mean of the numbers is",harmonical_mean)

但我总是得到错误的结果,我不知道为什么? 这些数字的算术平均值是 8.5 数字的几何平均值为 12.0 数字的调和平均值为 3.2727272727272725 enter image description here

您不断地重新计算均值,而不是摄取所有数字然后计算一次。我将计算移到了 while 循环之外:

import math

def fancy_mean():
    number=input("Please enter the numbers, one in each line: ")
    total_arithmetic=0
    multiplication_result_geometric=1
    harmonical_total=0
    count_of_numbers=0
    list_of_numbers=[]
    
    while number != "":
        number=float(number)
        list_of_numbers.append(number)
        count_of_numbers+=1
        number=input("Please enter the numbers, one in each line: ")

    for i in list_of_numbers:
        total_arithmetic=total_arithmetic+i
        arithmatic_mean=float(total_arithmetic/count_of_numbers)
        multiplication_result_geometric=multiplication_result_geometric*i
        geomatric_mean=float(math.sqrt(multiplication_result_geometric))
        harmonical_total=harmonical_total+(1/i)
        harmonical_mean=float(count_of_numbers/harmonical_total)

    if not list_of_numbers:
        return

    print("The arithmetic mean of the numbers is",arithmatic_mean)
    print("The geometric mean of the numbers is",geomatric_mean)
    print("The harmonic mean of the numbers is",harmonical_mean)

fancy_mean()

除非您有充分的理由不使用这些函数的现有实现,否则我建议您声明 fancy_mean 并使用 SciPy 和 geometric mean, harmonic mean, and mean 的 NumPy 实现。

此外,代码缺少 return 语句,这可能是因为可能存在无限循环(我假设缩进在您的环境中是正确的)。

这是您函数的 SciPy/NumPy 版本,没有输入新号码的提示:

from scipy.stats.mstats import gmean, hmean
import numpy as np

my_numbers = [4, 9]

def fancy_mean(numbers):
    return gmean(numbers), hmean(numbers), np.mean(numbers)

fancy_mean(my_numbers)

# >>> (6.0, 5.538461538461538, 6.5)

您可以通过将 print 语句移动到循环内、修复变量的大量拼写错误并在循环内请求新数字来计算中间均值。如果提供了一个空字符串并且您优雅地处理了非浮点输入,您可以使用 break 语句离开循环:

import math

def fancy_mean():
    arithmetic_total = 0
    multiplication_result_geometric = 1
    harmonical_total = 0
    numbers = []
    len_numbers = 0
    while True:
        number = input(f"\nPlease enter the next number, currently you have {numbers}:")
        if not number:      # empty string: exit
            break
        try:
            n = float(number)
            numbers.append(n)
        except ValueError:
            print("Not a number!")
            continue  # back to the start of the loop


        len_numbers += 1       # you can use len(numbers) instead as well
        
        # sum numbers / count numbers
        arithmetic_total += n
        arithmetic_mean = float(arithmetic_total/len_numbers)

        # nth root of product of n numbers 
        multiplication_result_geometric *= n
        geometric_mean= multiplication_result_geometric ** (1/len_numbers) 

        # count numbers / sum (1/number for number in numbers)
        harmonical_total += 1/n
        harmonical_mean = len_numbers / harmonical_total

        print("The arithmetic mean of the numbers is", arithmetic_mean)
        print("The geometric mean of the numbers is", geometric_mean)
        print("The harmonic mean of the numbers is", harmonical_mean)

fancy_mean()

输出:

Please enter the next number, currently you have []: 1
The arithmetic mean of the numbers is 1.0
The geometric mean of the numbers is 1.0
The harmonic mean of the numbers is 1.0

Please enter the next number, currently you have [1.0]: 4
The arithmetic mean of the numbers is 2.5
The geometric mean of the numbers is 2.0
The harmonic mean of the numbers is 1.6

Please enter the next number, currently you have [1.0, 4.0]: 4
The arithmetic mean of the numbers is 3.0
The geometric mean of the numbers is 2.5198420997897464
The harmonic mean of the numbers is 2.0