[Tutor] Statistic-Program Problems! Please Help Quickly!
steve at pearwood.info
Fri Oct 15 08:54:08 CEST 2010
On Fri, 15 Oct 2010 03:09:57 pm Colleen Glaeser wrote:
> So far, my program is as follows:
> Data = [[3,1],[4,3],[6, 4],[7, 6],[8, 8],[9, 8]]
> def X():
> accX = 0
> for item in Data:
> [x,y] = item
> accX = accX + x
> print (accX)
I see four problems with this function. The first three are minor,
stylistic problems. The fourth is the biggy -- it stops your function
from working correctly.
(1) The name X doesn't mean anything. Functions should have a name that
tells the reader what the function does. In this case, I
suggest "sumx", since it sums the x values.
(2) The function gets its input from a global variable, Data. This isn't
*wrong*, exactly, but it's usually inconvenient and leads to trouble
later on. It is often better to pass the Data as an argument to the
function, especially if you have more than one set of data to use.
Example: when you call the "len" function, to get the length of a list,
you do this:
len(my_list) # pass the list as an argument to the function
rather than this:
Data = my_list
len() # only looks at the global variable Data
(3) We can simplify the for-loop a little bit. Instead of this:
for item in Data:
[x,y] = item
you can do this:
for x,y in Data:
Since item is not used anywhere else, this saves time and code.
(4) This is a real problem. Your function doesn't return a result, it
merely prints it to the screen. This means it's impossible to store the
result for use later on, or to do calculations with it, or anything
like that. This is why you get the error message:
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
The error is a bit cryptic, but it means that when you try multiplying
Y() * Q() later on, neither function returns anything, so Python tries
multiplying None and None, which is impossible.
Fixing these three minor issues and one major problem, I get:
accumulator = 0
for (x,y) in data:
accumulator += x
To use this, you might do this:
my_first_data_set = [ [1,2], [3,4], [5,6] ]
my_second_data_set = [ [3,4], [5,6], [100, 0] ]
a = sumx(my_first_data_set)
b = sumx(my_second_data_set)
print "Sum of x from first set:", a
print "Sum of x from second set:", b
which should print:
Sum of x from first set: 9
Sum of x from second set: 108
You should make similar adjustments to Y() and the other functions, and
then see how the assignment goes.
More information about the Tutor