I'm still new at this but I think I am close. My assignment is to calculate the mean, median, and mode, then:
I would like to have the file more "readable". an example of the result I get now is:
(lp1
S'3,5,6'
p2
aF4.666666666666667
aF5
aF3
a.
Any help would be greatly appreciated!
Here is my code:
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
Try to use the json
module. It's easy to use and human-readable
import json
code...
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'
json.dump([user_in, mean(numbers), median(numbers), mode(numbers)], fp)
Then:
def print(fp):
user_in, mean, median, mode = json.load(fp)
print "\nYour inputs: ", user_in, '\n'
print " Mean = ", mean
print " Median = ", median
print " Mode = ", mode, '\n'