Need Help - Python Question

Thread Solved

Join Date: Apr 2007
Posts: 8
Reputation: olufunkky is an unknown quantity at this point 
Solved Threads: 0
olufunkky olufunkky is offline Offline
Newbie Poster

Need Help - Python Question

 
0
  #1
May 26th, 2007
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.

  1. count = 0
  2. sum = 0
  3. number = 1
  4. print 'Enter 0 to exit the list of numbers'
  5. while number != 0:
  6. number = input('Enter a number:')
  7. count = count + 1
  8. sum = sum + number
  9. count = count - 1
  10.  
  11. variableMean = lambda x: sum(x)/len(x)
  12. variableMedian = lambda x: x.sort() or x[len(x)//2]
  13. variableMode = lambda x: max([x.count(y),y] for y in x)[1]
  14.  
  15. s = 'variableMean(number)'
  16. y = 'variableMedian(number)'
  17. t = 'variableMode(number)'
  18.  
  19. def variableMedian(x):
  20. # don't modify original list
  21. return sorted(x)[len(x)/2]
  22.  
  23. def variableMode(x):
  24. # only iterate through x once (instead of len(x)times)
  25. counts = {}
  26. for items in x:
  27. counts[x] = counts.get(x, 0) + 1
  28. return max(count, key = counts._getitem_)
  29. return sorted(count, key = counts._getitem_.reverse == True) [0]
  30. x = (s, y, t)
  31. f = ("avg.py")
  32. import pickle
  33. pickle.dump((s, y, t), file('avg.pickle', 'w'))
  34. print 'Thank you! Would you like to see the results after calculating'
  35. print 'The mode, median, and mean? (Please enter Yes or No)'
  36. f = open("avg.py", "r")
  37. data = f.read()
  38. if raw_input == "Yes":
  39. f = open("avg.py", "r")
  40. data = f.read()
  41.  
  42. print 'The Mean average is:', sum/count
  43. print 'The Median is:', variableMedian
  44. 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.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Need Help - Python Question

 
0
  #2
May 26th, 2007
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 ...
  1. # create a list of numbers using a loop
  2.  
  3. num_list = []
  4. while True:
  5. number = input('Enter a number (zero to quit loop): ')
  6. if number == 0:
  7. break
  8. num_list.append(number)
  9.  
  10. # test it ...
  11. 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 ...
  1. # this list for testing only
  2. num_list = [7, 21, 11, 3, 9]
  3.  
  4. # convert the sum to a float to get a float result
  5. #mean = float(sum(num_list))/len(num_list)
  6. # or if you just want integer results use this
  7. mean = sum(num_list)/len(num_list)
  8. print mean # 10
  9.  
  10. print sorted(num_list) # [3, 7, 9, 11, 21]
  11. median = sorted(num_list)[len(num_list)/2]
  12. print median # 9
  13.  
  14. mode = max([num_list.count(y),y] for y in num_list)[1]
  15. print mode # 21
  16.  
  17. print
  18.  
  19. # save/pickle the results as a tuple (mean, median, mode)
  20. filename = 'MeanMedianMode.dat'
  21. import pickle
  22. fout = open(filename, "w")
  23. pickle.dump((mean, median, mode), fout)
  24. fout.close()
  25.  
  26. # load/pickle the tuple back in
  27. fin = open(filename, "r")
  28. mean, median, mode = pickle.load(fin)
  29. fin.close()
  30. # test it
  31. print mean, median, mode # 10 9 21
  32.  
  33. # pretty it up a little
  34. print 'mean =', mean
  35. print 'median =', median
  36. 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) ...
  1. # this is how you can read in a datafile list of numbers
  2. # (one number per line, no empty lines) into a Python list
  3. data = """7
  4. 21
  5. 11
  6. 3
  7. 9
  8. """
  9.  
  10. # create the data file first
  11. filename = 'numbers1.txt'
  12. fout = open(filename, "w")
  13. fout.write(data)
  14. fout.close()
  15.  
  16. # now read the data file into a Python list
  17. fin = open(filename, "r")
  18. num_list2 = fin.readlines()
  19. fin.close()
  20.  
  21. print num_list2 # ['7\n', '21\n', '11\n', '3\n', '9\n']
  22.  
  23. num_list3 = []
  24. for item in num_list2:
  25. # strip newline char and convert string to number
  26. # note that eval() handles integer or float number
  27. item = eval(item.strip())
  28. num_list3.append(item)
  29.  
  30. 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.
Last edited by vegaseat; May 26th, 2007 at 3:56 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Apr 2007
Posts: 8
Reputation: olufunkky is an unknown quantity at this point 
Solved Threads: 0
olufunkky olufunkky is offline Offline
Newbie Poster

Re: Need Help - Python Question

 
0
  #3
Jun 12th, 2007
Thanks for your help. It is well appreciated.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC