如何将数学方程式从函数写入文件?

时间:2018-10-04 17:04:10

标签: python python-3.x function file-writing

我正在尝试从文件中统计数据并计算平均值,中位数,最小值和最大值。 我已经能够做到这一点。

我要努力工作的地方是我需要给用户一个选择,将计算的统计信息保存到新文件中。它给我一个错误,说“ str”对象没有属性“ write”

有人知道如何将“ computed_stats”功能写入文件吗? 非常感谢您的帮助!

这是我的大部分代码的屏幕截图。我没有足够的屏幕空间来包含表格,该表格提示用户输入选择或加载数据的功能。他们似乎对这个问题并不重要。

def table():
    print("Choose an option:")
    print("1. Load data")
    print("2. Display computed statistics")
    print("3. Save computed statistics")
    print("4. Exit")

def load_data(filename):
    with open(filename) as f:
        for lines in f:
            numbers = lines.split()
            return(numbers)

def compute_stats(data_list):

    minimum = (min(data_list))
    maximum = (max(data_list))
    mean = (sum(data_list) / (len(data_list)))
    data = sorted(data_list)
    if (len(data) % 2) == 1:
        median = data[len(data) // 2]      
    else:
        median = (data[len(data) // 2] + data[len(data) // 2 - 1]) / 2
    return minimum, maximum, mean, median

def print_stats(data_list):
    minumum, maximum, mean, median = compute_stats(data_list)
    print(minimum)
    print(maximum)
    print(mean)
    print(median)


def save_stats(new_file):
    global comp_data    
    with open(new_file, 'w') as f:        
        f.close()



def main():


    selection = 0
    while selection != "4":
        table()
        selection = input("Choose a selection: ")
        print()

        if selection == "1":
            data_list = input("Enter the name of your file: ")
            data_list = load_data(data_list)
            data_list = [int(x) for x in data_list]
            print("Data read sucessfully \n")


        elif selection == "2":          
            print_stats(data_list)


        elif selection == "3":
            new_file = input("Enter File Name")
            save_stats(new_file)


main()

1 个答案:

答案 0 :(得分:1)

这里遇到的一个经典问题是,您将结果的表示与计算混淆了。在您的代码中,computed_stats函数既可以打印也可以计算。顺便说一句,它的名字很不好,像print_statistics之类的更好。通常,当您的函数名称不是自然地以动词开头时,它们的职责就定义不清。

对于第一个更改,我将执行以下操作:

def compute_statistics(data_list):
    # Do whatever computations you need but don't print anything
    minimum = #Insert computation for minimum here
    maximum = #Insert computation for maximum here
    mean = #Insert computation for mean here
    median = #Insert computation for median here
    return minimum, maximum, mean, median # whatever statistics you are computing

def print_statistics(data_list):
    minimum, maximum, mean, median=compute_statistics(data_list)
    # Put your printing logic here using the results from above

def save_statistics(file_name, data_list):
    minimum, maximum, mean, median=compute_statistics(data_list)
    with open(file_name,'w') as outfile:
        file.write(f"min = {minimum}\n")
        # Put all your saving logic here

如果您希望打印的版本看起来与保存的版本完全相同,则还可以添加一个用于生成该字符串的函数,可以从print_statisticssave_statistics进行调用。

稍后,您可能希望考虑如何更好地管理应用程序的状态,从而不必每次都重新计算统计信息。但这是另一个故事。