Surkaav S
Surkaav S

Reputation: 49

sum of each row and column in python without using numpy

I have the foll code in python:

 import random
    n=int(input("Enter the limit of your matrix:"))
    a=[[random.random()for i in range(n)],[random.random()for j in range(n)]]
    for i in range(0,n):
        for j in range(0,n):
            a[i][j]=int(input("Enter the element:"))
    for i in range(0,n):
        for j in range(0,n):
            if i==j:
                print a[i][j]
    for i in range(0,n):
        for j in range(0,n):
            if i==(n-j-1) or i==(n-j+1):
                print a[i][j]

but this doesnt take 9 inputs when limit is gn as 3. It shows error after taking 7 inputs. please help me in rectifing it.Iam not supposed to use numpy

Upvotes: 1

Views: 3648

Answers (3)

Irshad Bhat
Irshad Bhat

Reputation: 8709

You don't need to initialize the array with random values, since you are overwriting them. random() is a very time consuming function, although for small arrays it is not visible. You can create an n*n array without random() as:

>>> a = []
>>> for i in range(n):
...    tmp = []
...    for j in range(n):
...       tmp.append(int(input("Enter the element: ")))
...    a.append(tmp)
... 
Enter the element: 1
Enter the element: 2
Enter the element: 3
Enter the element: 4
Enter the element: 5
Enter the element: 6
Enter the element: 7
Enter the element: 8
Enter the element: 9
>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Also if you want to sum each row and column, here is the code:

>>> for i in a: print sum(i)  # sum of rows
... 
6
15
24
>>> for i in zip(*a): print sum(i) # sum of columns
... 
12
15
18

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117876

Creating a matrix

def createMatrix(n):
    import random
    return [[random.randint(1,9) for _ in range(n)] for _ in range(n)]

>>> createMatrix(3)
[[5, 3, 1],
 [3, 6, 7],
 [3, 2, 9]]

Summing all the values

def sumMatrix(m):
    return sum(sum(i) for i in m)

>>> sumMatrix(a)
39

Summing a specific column

def sumColumn(m, c):
    return sum(i[c] for i in m)

>>> sumColumn(a, 1)
11

Summing a specific row

def sumRow(m, r):
    return sum(m[r])

>>> sumRow(a, 0)
9

Upvotes: 4

aruisdante
aruisdante

Reputation: 9085

So the problem is that

a=[[random.random()for i in range(n)],[random.random()for j in range(n)]]

Is not a n*n matrix which is what you intended, it's a n*2 matrix. You want this instead:

a = [[random.random() for i in range(n)] for j in range(n)]

Instead. Also note if you're in python 2.7, replace range with xrange, as the former actually creates a list to iterate over (a waste of resources) where as the latter just iterates over the numbers without creating a list.

Upvotes: 2

Related Questions