我还是新手,但我认为我很接近。我的任务是计算平均值、中位数和众数,然后:
- 提示用户输入数字列表(提示:确保有一种方式让用户表明他们已完成提供数字列表)
- 打开一个包含数字列表的文件
- 计算数字列表的平均值、统计中位数和众数
- 将您的答案存储在另一个文件中
- 询问用户是否想查看答案,如果答案是肯定的,则打开文件并显示数字
我想让文件更“可读”。我现在得到的结果的一个例子是:
(lp1
S'3,5,6'
p2
aF4.666666666666667
aF5
aF3
a.
任何帮助将不胜感激!
这是我的代码:
def mean(numbers):
average = 0
for number in numbers:
average += number
return average / float(len(numbers))
def median(numbers):
middle = []
for number in numbers:
middle.append(number)
middle.sort()
middleValue = len(middle) / 2
if len(middle) % 2 == 1:
return middle[middleValue]
else:
return (middle[middleValue] + middle[middleValue - 1]) / 2
def mode(numbers):
frequency = {}
for number in numbers:
times = frequency.get(number, None)
if times == None:
frequency[number] = 1
else:
frequency[number] = times + 1
maxValue = max(frequency.values())
for modeFreq in frequency:
if frequency[modeFreq] == maxValue:
return modeFreq
import cPickle as pickle
def main():
user_in = raw_input("Enter a list of numbers seperated by commas: ")
numbers_as_strings = user_in.replace(' ', '').split(',')
numbers = [float(x) for x in numbers_as_strings]
if not user_in:
return 0
else:
print "\nYour inputs: ", user_in, '\n'
print " Mean = ", mean(numbers)
print " Median = ", median(numbers)
print " Mode = ", mode(numbers), '\n'
pckl_file = file("mean_medi_mode.txt", "w")
pickle.dump([user_in, mean(numbers),median(numbers),mode(numbers)],pckl_file)
main()
while True:
answer = raw_input('Would you like to open a file with your results? ')
if answer.strip() in "y Y yes Yes YES".split():
f = open("mean_medi_mode.txt", 'r')
for line in f:
print line,
print 'Done'
break
elif answer.strip() in "n N no No NO".split():
print 'Done'
break