Dynamic Matrix Input in Python - python

raw = input("Enret Number of Raws : ")
cols = input("Enter Number of Cols : ")
obj = []
mat = [[[] for j in range(raw)] for i in range(cols)]
for k in range(2):
for i in range(cols):
for j in range(raw):
number = int(input("Please Enter Elements of Matrix : "))
mat[i][j] = number
obj.append(mat)
print obj
Output:
Enret Number of Raws : 2
Enter Number of Cols : 2
Please Enter Elements of Matrix 1:9
Please Enter Elements of Matrix 1:3
Please Enter Elements of Matrix 1:7
Please Enter Elements of Matrix 1:1
[[[9, 3], [7, 1]]]
Please Enter Elements of Matrix 2:8
Please Enter Elements of Matrix 2:2
Please Enter Elements of Matrix 2:4
Please Enter Elements of Matrix 2:6
[[[8, 2], [4, 6]], [[8, 2], [4, 6]]]
After appending second Matrix in list, Value of 1st get change.

raw = input("Enret Number of Raws : ")
cols = input("Enter Number of Cols : ")
obj = []
for k in range(2):
mat = [[[] for j in range(raw)] for i in range(cols)]
for i in range(cols):
for j in range(raw):
number = int(input("Please Enter Elements of Matrix : "))
mat[i][j] = number
obj.append(mat)
print obj

raw = int(input("Enret Number of Raws : "))
cols = int(input("Enter Number of Cols : "))
mat=[]
for i in range(raw):
a=[]
for j in range(cols):
j=int(input("Enter Number in pocket ["+str(i)+"]["+str(j)+"]"))
a.append(j)
mat.append(a)
print(mat)

First read total number of rows and columns then iterate N times and take each row as input initially its stored as string but map(int,) makes each element into integer
R = int(input("Enter total Rows: "))
C = int(input("Enter total Columns: "))
matrix = [list(map(int,input().split())) for _ in range(R)]
print(matrix)
Input
Enter total Rows: 3
Enter total Columns: 3
1 2 3
4 5 6
7 8 9
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
When rows and cols are not given in online IDE it will throw EOF error you use input() when no input is given in such cases use
matrix = []
while True:
try:
matrix.append(list(map(int,input().split()))
except:
break

Related

How to generate a matrix with consecutive/continues integers like [ [1, 2, 3], [4, 5, 6], [7, 8, 9]... ]?

I have n rows and m columns I need a matrix which consists of consecutive m numbers like 1,2,3,4 this in each of the n rows that needs to be in ever increasing order.
example: 3 X 4 matrix\
**[\
[1, 2, 3, 4], \
[5, 6, 7, 8],\
[9, 10, 11, 12]\
]**
The intuition is very simple. What we need is our starting element in eaxh row should be the next element of the previous row's last element. That is the only tricky part in this problem.
For that we start our next row generation with arr[i-1][-1] to the arr[i-1][-1] + m. But for the first row generation we start from 1 since the matrix is empty.
Code
mat = []
n,m = map(int,input().split())
for row in range(n):
# if the row is starting row we start it with 1
# Else we assign k to the prev rows
if row == 0:
k = 1
else:
k = mat[row-1][-1] + 1
x = []
#the new row starts from previous rows last elemnt + 1
for j in range(k,k+m):
x.append(j)
mat.append(x)
print(mat)
First generate a continuous sequence of numbers and then adjust the format, with reference to either:(n and m represent the number of rows and columns respectively)
use the built-in functions, array to generate sequences, reshape to adjust the layout
import numpy as np
n, m = map(int, input().split())
res = np.arange(1, n*m+1).reshape(n, m)
print(res)
using list generative
items = list(range(1, m*n+1))
res = [items[i:i+m] for i in range(0, len(items), m)]
print(res)
here's a one liner to achieve that -
row, col = 3, 4
mat = [[col*i + j for j in range(1, col+1)] for i in range(row)]
print(mat)

How to print the sum of columns and rows in python?

I would like to print sum of each row and sum of each column of a two dimensional array, like this:
sum row1 = 123 (numbers are not real sums, just for example)
sum row2 = 123
sum row3 = 123
And the same with columns. I know how to do it in java, but dont know how to do it in python.
This is my code(missing code for sums of rows and columns, because I dont know how to do it):
from random import randint
dim1 = input("Insert first dimension: ")
dim1 = int(dim1)
dim2 = input("Insert second dimension: ")
dim2 = int(dim2)
table1d = []
for i in range(dim1):
table2d = []
for j in range(dim2):
table2d.append(randint(1, 170))
table1d.append(table2d)
print(table1d)
totalSum = sum(map(sum, table1d))
print(totalSum)
sumRows = 0
for i in range(0, len(table1d), 1):
sumRows += table1d[i]
For rows you need only
sums_in_rows = list(map(sum, table1d))
print(sums_in_rows)
For columns it needs more
sums_in_columns = [0]*len(table1d[0]) # create list for all results
for row in table1d:
for c, value in enumerate(row):
sums_in_columns[c] += value
print(sums_in_columns)
You can also convert it to numpy array and then you have
import numpy as np
arr = np.array(table1d)
print('rows:', arr.sum(axis=1))
print('cols:', arr.sum(axis=0))
print('total:', arr.sum())
from random import randint
dim1 = input("Insert first dimension: ")
dim1 = int(dim1)
dim2 = input("Insert second dimension: ")
dim2 = int(dim2)
table1d = []
#x = 0
for i in range(dim1):
table2d = []
for j in range(dim2):
table2d.append(randint(1, 170))
#table2d.append(x)
#x += 1
table1d.append(table2d)
print(table1d)
sums_in_rows = list(map(sum, table1d))
print(sums_in_rows)
sums_in_columns = [0]*len(table1d[0])
for row in table1d:
for c, value in enumerate(row):
sums_in_columns[c] += value
print(sums_in_columns)
import numpy as np
arr = np.array(table1d)
print(arr.sum(axis=1))
print(arr.sum(axis=0))
print(arr.sum())
import numpy as np
Columns:
np.array(table1d).sum(axis=0)
Rows:
np.array(table1d).sum(axis=1)
You can use list comprehensions and the sum function to obtain the desired result:
import random
rowCount = 3
colCount = 5
matrix = [ [random.randint(10,99) for _ in range(colCount)] for _ in range(rowCount) ]
for line in matrix:
print(line)
for row in range(rowCount):
print(f"sum row{row} = ",sum(matrix[row]))
for col in range(colCount):
print(f"sum column{col} = ",sum(row[col] for row in matrix))
[90, 62, 86, 19, 13]
[33, 93, 38, 17, 29]
[11, 96, 91, 66, 81]
sum row0 = 270
sum row1 = 210
sum row2 = 345
sum column0 = 134
sum column1 = 251
sum column2 = 215
sum column3 = 102
sum column4 = 123
Here is a simple and straightforward two-loop solution, if you want to do both the sums together.
container = [[1, 2, 3, 4],
[3, 2, 1, 5],
[4, 5, 6, 6]]
rowSum, colSum, i = [0]*len(container), [0]*len(container[0]), 0
while i < len(container):
j = 0
while j < len(container[0]):
rowSum[i] += container[i][j]
colSum[j] += container[i][j]
j += 1
i += 1
print(rowSum, colSum)
Hope it helps. ✌

Algorithm to find # elements less than target in a sorted Matrix in O(n)?

Design an algorithm that outputs the number of entries in A that are smaller than or equal to x. Your algorithm should run in O(n) time.
For example in the array below if my target was '5' then I would return 2 b/c 1 and 3 are smaller.
[1, 3, 5]
[2, 6, 9]
[3, 6, 10]
I gave it a shot with the code below which is close to working and I think it's O(n) ... the problem I see is if I don't have the # in my array I am not sure if I am returning the right value?
def findLessX(m,n,x):
i = 0
j = n-1
while (i < n and j >= 0):
if i == n or j == n:
print("n not found")
return (i+1)*(j+1)-1
if (m[i][j] == x):
print(" n Found at ", i , " ", j)
return (i+1)*(j+1)-1
elif (m[i][j] > x):
print(" Moving left one column")
j = j - 1
elif (m[i][j] < x):
print(" Moving down one row")
i = i + 1
print(" n Element not found so return max")
return (i)*(j+1)
# Driver code
x = 5
n = 3
m = [ [1, 3, 5],
[2, 6, 9],
[3, 6, 9]]
print("Count=", findLessX(m, n, x))
Inspect the Count and simple matrix above to see if soln works ~
If both columns and rows are sorted ascending, then for any given border value some stairs line does exist. It divides matrix into two parts - higher (and equal) and lower than border value. That line always goes left and down (if traversal starts from top right corner).
[1, 3, |5]
____|
[2,| 6, 9]
[3,| 6, 10]
So scan from top right corner, find starting cell for that line on the right or top edge, then follow the line, counting elements being left to it.
Complexity is linear, because line never turns back.
P.P.S. I hoped that you could write code with given clues
def countLessX(m,n,x):
col = n-1
count = 0
for row in range(n):
while (col >= 0) and (m[row] [col] >= x):
col = col - 1
count = count + col + 1
if col < 0: #early stop for loop
break
return count
# Driver code
n = 3
m = [ [1, 3, 5],
[2, 6, 9],
[3, 6, 9]]
for x in range(11):
print("x=", x, "Count=", countLessX(m, n, x))
x= 0 Count= 0
x= 1 Count= 0
x= 2 Count= 1
x= 3 Count= 2
x= 4 Count= 4
x= 5 Count= 4
x= 6 Count= 5
x= 7 Count= 7
x= 8 Count= 7
x= 9 Count= 7
x= 10 Count= 9
As mentioned in my comment your problem is not solveable in O(n) for most matrices. Some other thoughts:
Why count j downwards?
i and j can never become n
Here is a solution in O(n) that perhaps fullfills your needs.
Here is the adapted code:
def findLessX(m,n,x):
i = 0
j = 0
while True:
if i+1<n and m[i+1][j]<x:
i=i+1
elif j+1<n and m[i][j+1]<x:
j=j+1
else:
print("n found at ", i+1 , " ", j+1, "or element not found so return max")
return (i+1)*(j+1)
Both answers suggested above will result in O(n^2).
In worst case, the algorithms will inspect all n^2 elements in the matrix.

a simple sum of columns in a 2D list

import random
ROWS = 3
COLS = 3
def main():
values = [[0,0,0], [0,0,0], [0,0,0]]
for r in range(ROWS):
for c in range(COLS):
values[r][c] = random.randint(1, 4)
print('List:')
print(values)
print(sum(values[0]))
print(sum(values[1]))
print(sum(values[2]))
main()
This is the code that I have written and what I would like to do is display the the individual totals for each column. For example, the final result would look like:
Total of column 0 is 7
Total of column 1 is 6
Total of column 2 is 7
Builtin python lists are not very ideal for working with matrix-like data. I would highly suggest using numpy:
import numpy as np
l = np.array(values)
l.sum(axis=1)
However, if you really need to use python lists, one strategy is just to reduce your outer list with your desired output.
reducer = lambda x, y : [x[i] + y[i] for i in range(len(x)]
reduce(reducer, values)
You can simply reverse the order of ROWS and COLS in another pair of nested loops:
import random
ROWS = 3
COLS = 3
values = list()
for r in range(ROWS):
values.append(list())
for c in range(COLS):
values[r].append(random.randint(1, 4))
print('List:', values, sep="\n")
for c in range(COLS):
sum = 0
for r in range(ROWS):
sum += values[r][c]
print("Total of column {} is {}".format(c, sum))
Produces:
List:
[[3, 2, 4], [4, 3, 4], [4, 2, 3]]
Total of column 0 is 11
Total of column 1 is 7
Total of column 2 is 11
You can try :
import random
ROWS=3
COLS=3
def main():
values = []
for i in range(ROWS):
list1=[]
for j in range(COLS):
val =random.randint(1,4)
list1.append(val)
values.append(list1)
print (values)
for col in range(COLS):
sum = 0
for row in range(ROWS):
sum += values[row][col]
print("Total of column "+str(col)+" is " +str(sum))
main()
[[4, 1, 2], [2, 3, 4], [3, 3, 1]]
Total of column 0 is 9
Total of column 1 is 7
Total of column 2 is 7
I ended up using something which now seems quite simple:
thank you for your responses
values = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for r in range(ROWS):
for c in range(COLS):
values[r][c] = random.randint(1, 4)
print('List:')
print(values)
print('Total of row 0 is', sum(values[0]))
print('Total of row 1 is', sum(values[1]))
print('Total of row 2 is', sum(values[2]))
valuescolumn1 = [row[0] for row in values]
print('Total of column 0 is', sum(valuescolumn1))
valuescolumn2 = [row[1] for row in values]
print('Total of column 1 is', sum(valuescolumn2))
valuescolumn3 = [row[1] for row in values]
print('Total of column 2 is', sum(valuescolumn3))

How to input matrix (2D list) in Python?

I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6]. Same things happen when I input other m by n matrix, the code yields an m by n matrix whose rows are identical.
Perhaps you can help me to find what is wrong with my code.
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the number of columns
for j in range (0,n):
columns += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = columns
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
The problem is on the initialization step.
for i in range (0,m):
matrix[i] = columns
This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes - every other column will change:
>>> for i in range (0,m):
... matrix[i] = columns
...
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]
You can initialize your matrix in a nested loop, like this:
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
or, in a one-liner by using list comprehension:
matrix = [[0 for j in range(n)] for i in range(m)]
or:
matrix = [x[:] for x in [[0]*n]*m]
See also:
How to initialize a two-dimensional array in Python?
Hope that helps.
you can accept a 2D list in python this way ...
simply
arr2d = [[j for j in input().strip()] for i in range(n)]
# n is no of rows
for characters
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = list(input().strip())
print(a)
or
n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
a[i].append(list(input().strip()))
print(a)
for numbers
n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
a[i] = [int(j) for j in input().strip().split(" ")]
print(a)
where n is no of elements in columns while m is no of elements in a row.
In pythonic way, this will create a list of list
If the input is formatted like this,
1 2 3
4 5 6
7 8 9
a one liner can be used
mat = [list(map(int,input().split())) for i in range(row)]
explanation with example:
input() takes a string as input. "1 2 3"
split() splits the string by whitespaces and returns a
list of strings. ["1", "2", "3"]
list(map(int, ...)) transforms/maps the list of strings into a list of ints. [1, 2, 3]
All these steps are done row times and these lists are stored in another list.[[1, 2, 3], [4, 5, 6], [7, 8, 9]], row = 3
If you want to take n lines of input where each line contains m space separated integers like:
1 2 3
4 5 6
7 8 9
Then you can use:
a=[] // declaration
for i in range(0,n): //where n is the no. of lines you want
a.append([int(j) for j in input().split()]) // for taking m space separated integers as input
Then print whatever you want like for the above input:
print(a[1][1])
O/P would be 5 for 0 based indexing
Apart from the accepted answer, you can also initialise your rows in the following manner -
matrix[i] = [0]*n
Therefore, the following piece of code will work -
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
This code takes number of row and column from user then takes elements and displays as a matrix.
m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
b = []
print("{0} Row".format(i))
for j in range(1,n+1):
b.append(int(input("{0} Column: " .format(j))))
a.append(b)
print(a)
If your matrix is given in row manner like below, where size is s*s here s=5
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
then you can use this
s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]
your matrix will be 'arr'
m,n=map(int,input().split()) # m - number of rows; n - number of columns;
matrix = [[int(j) for j in input().split()[:n]] for i in range(m)]
for i in matrix:print(i)
no_of_rows = 3 # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)
You can make any dimension of list
list=[]
n= int(input())
for i in range(0,n) :
#num = input()
list.append(input().split())
print(list)
output:
Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:
rows = int(input('Number of rows: '))
cols = int(input('Number of columns: '))
matrix = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)]
with 2 rows and 3 columns matrix will be [[1, 2, 3], [4, 5, 6]], with 3 rows and 2 columns matrix will be [[1, 2], [3, 4], [5, 6]] etc.
a = []
b = []
m=input("enter no of rows: ")
n=input("enter no of coloumns: ")
for i in range(n):
a = []
for j in range(m):
a.append(input())
b.append(a)
Input : 1 2 3 4 5 6 7 8 9
Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]
row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
print('value of i: ',i)
a=list(map(int,input().split()))
print(a)
b.append(a)
print(b)
print(row)
Output:
2 3
value of i:0
1 2 4 5
[1, 2, 4, 5]
value of i: 1
2 4 5 6
[2, 4, 5, 6]
[[1, 2, 4, 5], [2, 4, 5, 6]]
[2, 3]
Note: this code in case of control.it only control no. Of rows but we can enter any number of column we want i.e row[0]=2 so be careful. This is not the code where you can control no of columns.
a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
for j in range(n):
b.append(int(input()))
a.append(b)
print("Here your {} column {}".format(i+1,a))
b=[]
for m in range(n):
print(a[m])
works perfectly
rows, columns = list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(rows):
a=list(map(int,input().split()))
b.append(a)
print(b)
input
2 3
1 2 3
4 5 6
output
[[1, 2, 3], [4, 5, 6]]
I used numpy library and it works fine for me. Its just a single line and easy to understand.
The input needs to be in a single size separated by space and the reshape converts the list into shape you want. Here (2,2) resizes the list of 4 elements into 2*2 matrix.
Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.
import numpy as np
a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)
print(a)
Input
array([[1, 2],
[3, 4]])
Output

Categories

Resources