views:

105

answers:

3

I know it's because of n, but n is supposed to be any variable, and left as n, this is what I have:

def average(n):
    if n >= 0:
        avg = sum((range(1:int(n)))/float(len(range(1:int(n)))))
    print avg

how do I fix it?

A: 

If your range is always 1:n, why don't you just use this:

avg = sum((range(1:int(n)))/float(n))

Or maybe I am not understanding your question...

Matthew Jones
+1  A: 

I may be wrong but range(1:int(n)) doesn't look like syntactically correct and parenthesis don't match. You may want to calculate the average of numbers in the range of 0 to n. In that case, I would replace your code like this:

def average(n):
if n >= 0:
    avg = sum((range(int(n))))/float(n)
print avg
JP
+1 for you! Totally missed the parens mismatch. Nice!
Matthew Jones
It doesn't calculate the proper average, e.g. if I use that code and plug in 3 for n the average should still be 2 but Python outputs 1.0
CP
range(n) returns an array of integers between [0..n[; for 3, that would be [0,¸1, 2]; sum() would return 3, and number of elements in the list is... 3; therefore, 3/3 == 1.0
JP
+2  A: 

The summation of x from 1 to n is simply (n + 1) * (n / 2). The number of elements being summed is n . Do a little simplification and your new function is

def average(n):
    return (n + 1) / 2.0

You'll have to adjust this if you actually wanted Python's behavior of an exclusive upper-bound for range() (i.e., having average(10) return the average of the sum of values 1 - 9 instead of 1 - 10).

jamessan
Thank-you, I know how to change it to include the extra sum, I wanted to know how to fix my original try, but I suppose the simplest version is better, thank-you again.
CP
Then you're being bitten by range()'s behavior. range(1, 10) returns [1, 2, 3, 4, 5, 6, 7, 8, 9]. So you want range(1, n+1).
jamessan