Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This program is supposed to:
put the sum of the numbers up the diagonal in a variable

and the ones under the diagonal in another variable

and the ones on the diagonal in another variable.


from numpy import *
x=6;m=array(([[int]*x]*x))
m[0,0]=0
m[0,1]=1
m[0,2]=2
m[1,0]=3
m[1,1]=4
m[1,2]=5
m[2,0]=6
m[2,1]=7
m[2,2]=8
m[3,0]=0
m[3,1]=1
m[0,2]=2
m[1,0]=3
m[1,1]=4
m[1,2]=5
m[2,0]=6
m[2,1]=7
m[2,2]=8
print(m)
def aff(m,x):
    s1=0
    s2=0
    s3=0
    for i in range(x):
        for j in range(x):
            if j<i:
                s2=s2+m[i,j]
            elif j>i :
                s1=s1+m[i,j]
            else:
                s3=s3+m[i,j]
    return s1,s2,s3
aff(m,x)


the problem is in this sum expression:
s2=s2+m[i,j]

it says
s1=s1+m[i,j]
TypeError: unsupported operand type(s) for +: 'int' and 'type'


What I have tried:

asking you guys , i didn't find a soultion am new
Posted
Updated 24-Nov-22 22:47pm
Comments
Richard MacCutchan 25-Nov-22 4:39am    
You have 6 rows and 6 columns in your array but you have not initialised them all.

1 solution

Quote:
Python
m=array(([[int]*x]*x))
That creates a 6x6 array with each element initialized to <class 'int'>.

You only set the first three columns of the first three rows, and the first two columns of the fourth row. All other values retain their default value of <class 'int'>.

You then try to add an int to a <class 'int'>, which is not a supported operation.

Change your array declaration to:
Python
m=array(([[0]*x]*x))
and your code will run successfully. Whether or not it produces the expected answer is up to you - I'd suggest you need to review your array initialization code, since you're not setting every element, and you're setting some elements twice.
 
Share this answer
 
Comments
CPallini 25-Nov-22 5:38am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900