0

Please I need help with this question. I have been trying to solve it, was able to solve a part, but not completely through with it

QUESTION:

Write a program that allows you to do the following five Operations:
a. 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)
b. Open a file that contains a list of numbers
c. Compute the average, statistical median, and mode of the list of numbers
d. Store your answers in another file
e. Asks the user whether they want to see the answers and if the answer is yes, opens the file and displays the numbers

This is what I come up with:

# This program will ask for a user to input numbers. The numbers will then be calculated
# Open a file that contains a list of numbers.
# Compute the average, statistical mean, and median.
# Store your answers in another file
# Ask user whether they want to see the ansers and if the answer is yes, open the file and displays the numbers.

count = 0
sum = 0
number = 1
print 'Enter 0 to exit the list of numbers'
while number != 0:
        number = input('Enter a number:')
        count = count + 1
        sum = sum + number
        count = count - 1
 
variableMean = lambda x: sum(x)/len(x)
variableMedian = lambda x: x.sort() or x[len(x)//2]
variableMode = lambda x: max([x.count(y),y] for y in x)[1]
 
s = 'variableMean(number)'
y = 'variableMedian(number)'
t = 'variableMode(number)'
 
def variableMedian(x):
    # don't modify original list
    return sorted(x)[len(x)/2]
 
def variableMode(x):
    # only iterate through x once (instead of len(x)times)
    counts = {}
    for items in x:
        counts[x] = counts.get(x, 0) + 1
        return max(count, key = counts._getitem_)
        return sorted(count, key = counts._getitem_.reverse == True) [0]
x = (s, y, t)
f = ("avg.py")
import pickle
pickle.dump((s, y, t), file('avg.pickle', 'w'))
print 'Thank you! Would you like to see the results after calculating'
print 'The mode, median, and mean? (Please enter Yes or No)'
f = open("avg.py", "r")
data = f.read()
if raw_input == "Yes":
    f = open("avg.py", "r")
    data = f.read()
 
    print 'The Mean average is:', sum/count
    print 'The Median is:', variableMedian
    print 'The Mode is:', variableMode

And the oputput I have after running the program is:

>>> 
Enter 0 to exit the list of numbers
Enter a number:3
Enter a number:6
Enter a number:9
Enter a number:12
Enter a number:0
Thank you! Would you like to see the results after calculating
The mode, median, and mean? (Please enter Yes or No)
>>> 'Yes'
'Yes'
>>> variableMean = lambda x: sum(x)/len(x)
>>> variableMedian = lambda x: x.sort() or x[len(x)//2]
>>> variableMode = lambda x: max([x.count(y),y] for y in x)[1]
>>> 
>>> s = 'variableMean(number)'
>>> y = 'variableMedian(number)'
>>> t = 'variableMode(number)'
>>> 
>>> def variable_median(x):
 # don't modify original list
 return sorted(x)[len(x)/2]
>>> def variable_mode(x):
 # only iterate through x once (instead of len(x)times)
 counts = {}
 for items in x:
  counts[x] = counts.get(x, 0) + 1
  return max(count, key = counts._getitem_)
  return sorted(count, key = counts._getitem_.reverse == True) [0]
 
>>> x = (s, y, t)
>>> f = ("avg.py")
>>> import pickle
>>> pickle.dump((s, y, t), file('avg.pickle', 'w'))
>>> 
>>> f = open("avg.py", "r")
>>> data = f.read()
>>> 
>>> 
KeyboardInterrupt
>>> print 'The Mean average is:', sum/count
The Mean average is: 7
>>> print 'The Median is:', variable_median
The Median is: <function variable_median at 0x00C429F0>
>>> 
>>> print 'The Mode is:', mode
The Mode is:
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
 print 'The Mode is:', mode
NameError: name 'mode' is not defined
>>> print 'The Mode is:', variablemode(number)
The Mode is:
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
 print 'The Mode is:', variablemode(number)
NameError: name 'variablemode' is not defined
>>> print 'The Mode is:', variableMode(number)
The Mode is:
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
 print 'The Mode is:', variableMode(number)
File "<pyshell#3>", line 1, in <lambda>
 variableMode = lambda x: max([x.count(y),y] for y in x)[1]
TypeError: 'int' object is not iterable
>>> print 'The Mode is:', variable_mode
The Mode is: <function variable_mode at 0x00C42A30>
>>> print 'The Mode is:', variableMode
The Mode is: <function <lambda> at 0x00C42C30>
>>>

I have not been able to get the value for MEDIAN and MODE yet. Can anyone please help me out?

Thanks.

2
Contributors
2
Replies
7
Views
9 Years
Discussion Span
Last Post by olufunkky
0

Use the Python shell (with the ugly >>> prompts) only for simple testing of one liners. For programming use an editor or better an IDE like IDLE or DrPython. This will save the program as a .py file.

Write the program in parts you can test out ...

# create a list of numbers using a loop
 
num_list = []
while True:
    number = input('Enter a number (zero to quit loop): ')
    if number == 0:
        break
    num_list.append(number)
 
# test it ...
print num_list  # for instance [7, 21, 11, 3, 9]

Now use the list to get your statistical results. So you don't have to enter all those numbers over and over again give the num_list some values. Remove the first 2 lines later, as you add this code to the first part ...

# this list for testing only
num_list = [7, 21, 11, 3, 9]
 
# convert the sum to a float to get a float result
#mean = float(sum(num_list))/len(num_list)
# or if you just want integer results use this
mean = sum(num_list)/len(num_list)
print mean  #  10
 
print sorted(num_list)  # [3, 7, 9, 11, 21]
median = sorted(num_list)[len(num_list)/2]
print median  # 9
 
mode = max([num_list.count(y),y] for y in num_list)[1]
print mode  # 21
 
print
 
# save/pickle the results as a tuple (mean, median, mode)
filename = 'MeanMedianMode.dat'
import pickle
fout = open(filename, "w")
pickle.dump((mean, median, mode), fout)
fout.close()
 
# load/pickle the tuple back in
fin = open(filename, "r")
mean, median, mode = pickle.load(fin)
fin.close()
# test it
print mean, median, mode  # 10 9 21
 
# pretty it up a little
print 'mean   =', mean
print 'median =', median
print 'mode   =', mode

Last not least, this is how you would read a data file of a list of numbers into a Python list (you have to create the file first) ...

# this is how you can read in a datafile list of numbers 
# (one number per line, no empty lines) into a Python list
data = """7
21
11
3
9
"""
 
# create the data file first
filename = 'numbers1.txt'
fout = open(filename, "w")
fout.write(data)
fout.close()
 
# now read the data file into a Python list
fin = open(filename, "r")
num_list2 = fin.readlines()
fin.close()
 
print num_list2  # ['7\n', '21\n', '11\n', '3\n', '9\n']
 
num_list3 = []
for item in num_list2:
    # strip newline char and convert string to number
    # note that eval() handles integer or float number
    item = eval(item.strip())
    num_list3.append(item)
 
print num_list3  # [7, 21, 11, 3, 9]

Read thought the code, test it, try to make sense out of it, and then combine the whole program from the working parts. Now you can comment out many of the test print lines. Copy, cut and paste operations of a good editor will make that easy.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.