过去几个小时一直试图解决这个问题,我找不到解决办法!基本上我们必须编写一个程序来打开一个文件,从中获取数字,并计算上述内容(平均值,最小值,最大值,标准派生值)。以下是我目前的情况:
def get_numbers():
# Open a file for reading.
infile = open('inNumbers.txt', 'r')
# Read the numbers from the file.
line = infile.readline()
while line != '':
print(line)
line = infile.readline()
infile.close()
def mean(nums):
sum = 0.0
for num in nums:
sum = sum + num
return sum / len(nums)
def stdDev(nums, xbar):
sumDevSq = 0.0
for num in nums:
dev = xbar - num
sumDevSq = sumDevSq + dev * dev
return sqrt(sumDevSq/(len(nums)-1))
def min():
showFile = open("inNumbers.txt", 'r')
lowest = None
for line in showFile:
tokens = line.split(',')
value = min(tokens[:2])
if lowest == None:
lowest = value
if value < lowest:
lowest = value
def main():
print("This program computes mean, maximum, minimum and standard deviation.")
data = get_numbers()
xbar = mean(data)
std = stdDev(data, xbar)
print("\nThe mean is", xbar)
print("The standard deviation is", std)
print("The minimum is", value)
main()的
答案 0 :(得分:1)
正如我所指出的那样,在尝试解决当前问题之前,你应该首先阅读一些关于编程的基本引子,否则任何答案都不会帮助你,而只会创造一个货币崇拜的新门徒。 / p>
然而,这里是你的代码(虽然我不确定std-dev的公式):
#open file
with open('inNumbers.txt', 'r') as f:
#read lines, strip trailing newlines, and convert to float if not empty
numbers = [float(x) for x in (x.strip() for x in f) if x]
avg = sum(numbers) / len(numbers)
sdv = (sum((n - avg) ** 2 for n in numbers) / len(numbers)) ** .5
print('The arithmetic mean is {}'.format(avg))
print('The standard deviation is {}'.format(sdv))
print('The minimum is {}.'.format(min(numbers)))
也许你可以从中获取一些有用的东西。
答案 1 :(得分:0)
了解包含数字的文件的外观非常重要。但我将从您的示例代码中假设每行有一个浮点数。如果你已经安装了numpy会更容易。我猜这是默认在Mac上。所以一步一步:
import numpy
#define a function that will just open your file containing numbers and get
#all data into a list of floats
def getNumbers(file):
numbers = []
with open(file, 'r') as numbers_file:
for line in numbers_file.readlines():
numbers.append(float(line.strip('\n').strip()))
return numbers
#get data from 'numbers.txt' into a list named 'num_list'
num_list = getNumbers('numbers.txt')
#print what you need
print 'Maximum is %g' %max(num_list)
print 'Minimum is %g' %min(num_list)
print 'Average is %g' %numpy.mean(num_list)
print 'Standard deviation is %g' %numpy.std(num_list)
#if you do not have numpy
my_avg = sum(num_list)/len(num_list)
print 'Average is %g' %my_avg
#you need to do some reading for the std-dev formula :)