Search code examples
pythonfileprintingpickleraw-input

How can I make results human readable when printing to a file?


I'm still new at this but I think I am close. My assignment is to calculate the mean, median, and mode, then:

  • Prompt the user to input a list of numbers (Hint: be sure to have a way for the user to indicate that they are done finished providing the list of numbers)
  • Open a file that contains a list of numbers
  • Compute the average, statistical median, and mode of the list of numbers
  • Store your answers in another file
  • Asks the user whether they want to see the answers and if the answer is yes, opens the file and displays the numbers

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

Solution

  • 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'