NOOB coding help....
Steven Bethard
steven.bethard at gmail.com
Mon Feb 21 23:37:07 EST 2005
Igorati wrote:
> list = [ ]
> a = 1
> print 'Enter numbers to add to the list. (Enter 0 to quit.)'
> while a != 0 :
> a = input('Number? ')
> list.append(a)
> zero = list.index(0)
> del list[zero]
> list.sort()
A simpler approach is to use the second form of the builtin iter
function which takes a callable and a sentinel:
py> def getint():
... return int(raw_input('Number? '))
...
py> numbers = sorted(iter(getint, 0))
Number? 3
Number? 7
Number? 5
Number? 2
Number? 0
py> numbers
[2, 3, 5, 7]
Note that I've renamed 'list' to 'numbers' so as not to hide the builtin
type 'list'.
> 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(list)
> y = variableMedian(list)
> t = variableMode (list)
See "Inappropriate use of Lambda" in
http://www.python.org/moin/DubiousPython.
Lambdas aside, some alternate possibilities for these are:
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 item in x:
counts[x] = counts.get(x, 0) + 1
# in Python 2.5 you'll be able to do
# return max(counts, key=counts.__getitem__)
return sorted(counts, key=counts.__getitem__, reverse=True)[0]
Note also that you probably want 'from __future__ import divsion' at the
top of your file or variableMean will sometimes give you an int, not a
float.
> x = (s,y,t)
> inp = open ("Wade_StoddardSLP3-2.py", "r")
> outp = open ("avg.py", "w")
> f = ("avg.py")
> for x in inp:
> outp.write(x)
> import pickle
> pickle.dump(x, f)
If you want to save s, y and t to a file, you probably want to do
something like:
pickle.dump((s, y, t), file('avg.pickle', 'w'))
I don't know why you've opened Wade_StoddardSLP3-2.py, or why you write
that to avg.py, but pickle.dump takes a file object as the second
parameter, and you're passing it a string object, "avg.py".
> f = open("avg.py","r")
> avg.py = f.read()
> print 'The Mean average is:', mean
> print 'The Median is:', meadian
> print 'The Mode is:', mode
mean, median, mode = pickle.load(file('avg.pickle'))
print 'The Mean average is:', mean
print 'The Median is:', meadian
print 'The Mode is:', mode
HTH,
STeVe
More information about the Python-list
mailing list