Row sum?

6 views
Skip to first unread message

Afif Khaja

unread,
May 6, 2013, 12:50:59 AM5/6/13
to MCS 260 Google group
What's wrong with this code? It's giving me an out of range error when sum += a[m][n]:
 
# find row sums of 2d array
def rowsum(a,m,n):
    rsum = [0.0 for i in range(m)]
    for i in range(m):
        sum = 0
        for j in range(n):
            sum += a[m][n]
        rsum[i] = sum
    return rsum
 
a = [[4,3,2],
     [2,4,6],
     [7,1,5]]

print rowsum(a,3,3)

S.F. Kyale

unread,
May 6, 2013, 3:20:56 AM5/6/13
to Afif Khaja, MCS 260 Google group
it looks like you're referencing the bottom left item in the array continuously.
a[m][n] will always be the maximum row, maximum column.
If you use a, you should be getting 15 all the way (5+5+5).


--
You received this message because you are subscribed to the Google Groups "uic-mcs260-s13" group.
To unsubscribe from this group and stop receiving emails from it, send an email to uic-mcs260-s1...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Jeremy Kun

unread,
May 6, 2013, 10:11:33 AM5/6/13
to S.F. Kyale, Afif Khaja, MCS 260 Google group
Soren is right. You need to use the indexing variables i and j you defined, not the limits n and m (which will always be one past the maximum allowable index).

Jeremy Kun
Mathematics Graduate Student
University of Illinois at Chicago

Afif Khaja

unread,
May 6, 2013, 12:33:21 PM5/6/13
to MCS 260 Google group
I see. Thanks
Reply all
Reply to author
Forward
0 new messages