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
Related
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)
I want to maximize the following function:
f(i, j, k) = min(A(i, j), B(j, k))
Where A and B are matrices and i, j and k are indices that range up to the respective dimensions of the matrices. I would like to find (i, j, k) such that f(i, j, k) is maximized. I am currently doing that as follows:
import numpy as np
import itertools
shape_a = (100 , 150)
shape_b = (shape_a[1], 200)
A = np.random.rand(shape_a[0], shape_a[1])
B = np.random.rand(shape_b[0], shape_b[1])
# All the different i,j,k
combinations = itertools.product(np.arange(shape_a[0]), np.arange(shape_a[1]), np.arange(shape_b[1]))
combinations = np.asarray(list(combinations))
A_vals = A[combinations[:, 0], combinations[:, 1]]
B_vals = B[combinations[:, 1], combinations[:, 2]]
f = np.min([A_vals, B_vals], axis=0)
best_indices = combinations[np.argmax(f)]
print(best_indices)
[ 49 14 136]
This is faster than iterating over all (i, j, k), but a lot of (and most of the) time is spent constructing the A_vals and B_vals matrices. This is unfortunate, because they contain many many duplicate values as the same i, j and k appear multiple times. Is there a way to do this where (1) the speed of numpy's matrix computation can be preserved and (2) I don't have to construct the memory-intensive A_vals and B_vals arrays.
In other languages you could maybe construct the matrices so that they container pointers to A and B, but I do not see how to achieve this in Python.
Perhaps you could re-evaluate how you look at the problem in context of what min and max actually do. Say you have the following concrete example:
>>> np.random.seed(1)
>>> print(A := np.random.randint(10, size=(4, 5)))
[[5 8 9 5 0]
[0 1 7 6 9]
[2 4 5 2 4]
[2 4 7 7 9]]
>>> print(B := np.random.randint(10, size=(5, 3)))
[[1 7 0]
[6 9 9]
[7 6 9]
[1 0 1]
[8 8 3]]
You are looking for a pair of numbers in A and B such that the column in A is the same as the row of B, and the you get the maximum smaller number.
For any set of numbers, the largest pairwise minimum happens when you take the two largest numbers. You are therefore looking for the max in each column of A, row of B, the minimum of those pairs, and then the maximum of that. Here is a relatively simple formulation of the solution:
candidate_i = A.argmax(axis=0)
candidate_k = B.argmax(axis=1)
j = np.minimum(A[candidate_i, np.arange(A.shape[1])], B[np.arange(B.shape[0]), candidate_k]).argmax()
i = candidate_i[j]
k = candidate_k[j]
And indeed, you see that
>>> i, j, k
(0, 2, 2)
>>> A[i, j]
9
>>> B[j, k]
9
If there are collisions, argmax will always pick the first option.
Your values i,j,k are determined by the index of the maximum value from the set {A,B}. You can simply use np.argmax().
if np.max(A) < np.max(B):
ind = np.unravel_index(np.argmax(A),A.shape)
else:
ind = np.unravel_index(np.argmax(B),B.shape)
It will return only two values, either i,j if max({A,B}) = max({A}) or j,k if max({A,B}) = max({B}). But if for example you get i,j then k can be any value that fit the shape of the array B, so select randomly one of this value.
If you also need to maximize the other value then:
if np.max(A) < np.max(B):
ind = np.unravel_index(np.argmax(A),A.shape)
ind = ind + (np.argmax(B[ind[1],:]),)
else:
ind = np.unravel_index(np.argmax(B),B.shape)
ind = (np.argmax(A[:,ind[0]]),) + ind
Trying to make a matrix alphabet pattern. The desired output should look like this:
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
I have found this solution for the matrix number pattern:
Input: 4
N = int(input('Enter N value:'))
k = (2 * N) - 1
low = 0
high = k - 1
value = N
matrix = [[0 for i in range(k)] for j in range(k)]
for i in range(N):
for j in range(low, high + 1):
matrix[i][j] = value
for j in range(low + 1, high + 1):
matrix[j][i] = value
for j in range(low + 1, high + 1):
matrix[high][j] = value
for j in range(low + 1, high):
matrix[j][high] = value
low = low + 1
high = high - 1
value = value - 1
for i in range(k):
for j in range(k):
print(matrix[i][j], end =' ')
print()
Output:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
Not sure if this matrix number pattern code is the smoothest solution.
It seems you just need to pass from digits to uppercase letters, also you don't need the extra variables low and value, just use the existing N and i
from string import ascii_uppercase # simple string of all alphabet
N = int(input('Enter N value:'))
k = (2 * N) - 1
high = k - 1
matrix = [[0 for _ in range(k)] for _ in range(k)]
for i in range(N):
for j in range(i, high + 1):
matrix[i][j] = N - i
for j in range(i + 1, high + 1):
matrix[j][i] = N - i
for j in range(i + 1, high + 1):
matrix[high][j] = N - i
for j in range(i + 1, high):
matrix[j][high] = N - i
high = high - 1
for i in range(k):
for j in range(k):
print(ascii_uppercase[matrix[i][j] - 1], end='')
print()
consider it as a distance from the center of the matrix with an offset.
[[int(max(abs((n-1)/2-i),abs((n-1)/2-j)))+1 for i in range(n)] for j in range(n)]
[[4, 4, 4, 4, 4, 4, 4],
[4, 3, 3, 3, 3, 3, 4],
[4, 3, 2, 2, 2, 3, 4],
[4, 3, 2, 1, 2, 3, 4],
[4, 3, 2, 2, 2, 3, 4],
[4, 3, 3, 3, 3, 3, 4],
[4, 4, 4, 4, 4, 4, 4]]
here n is an odd value, the center of the matrix is (n-1)/2. Since you want "1" at the center add one as offset, division converts the numbers to float format, so int() for nice formatting. List comprehension can be converted to nested loop but seems fine this way since eliminates the matrix initialization step.
The distance is called Chebyshev distance (or chessboard distance).
To covert the matrix into a String array, convert digits to corresponding chars and join the rows. At this point readability fails
[''.join([chr(ord('A')+int(max(abs((n-1)/2-i),abs((n-1)/2-j)))) for i in range(n)]) for j in range(n)]
['DDDDDDD', 'DCCCCCD', 'DCBBBCD', 'DCBABCD', 'DCBBBCD', 'DCCCCCD', 'DDDDDDD']
use functions!
def chebDist(i,j,n):
return int(max(abs((n-1)/2-i),abs((n-1)/2-j)))
def toChar(d):
return chr(ord('A')+d-1)
[''.join([toChar(chebDist(i,j,n)+1) for i in range(n)]) for j in range(n)]
will give you
['DDDDDDD', 'DCCCCCD', 'DCBBBCD', 'DCBABCD', 'DCBBBCD', 'DCCCCCD', 'DDDDDDD']
or perhaps this format
print('\n'.join([''.join([toChar(chebDist(i,j,n)+1) for i in range(n)]) for j in range(n)]))
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
readable and with reusable functions!
You can perhaps make it more readable by separating the conversions, tradeoff is efficiency due to intermediate values
first create the numerical matrix
m=[[chebDist(i,j,n)+1 for i in range(n)] for j in range(n)]
convert to char mapping
c=[[toChar(e) for e in row] for row in m]
convert to String representation and print.
print('\n'.join([''.join(row) for row in c]))
UPDATE
Finally, all wrapped up into 4 generic functions and 2 lines of code.
def chebDist(i,j,n):
return int(max(abs((n-1)/2-i),abs((n-1)/2-j)))
def toChar(d):
return chr(ord('A')+d-1)
def map2(f,m):
return [[f(e) for e in row] for row in m]
def toString(a):
return '\n'.join(map(''.join,a))
m=[[chebDist(i,j,n)+1 for i in range(n)] for j in range(n)]
print(toString(map2(toChar,m)))
We can solve everything in a single input line and a single output line:
N = int(input('Enter N value:'))
print('\n'.join([''.join([chr(64+max(max(N-i,N-j),max(i-N+2,j-N+2))) for i in range(2*N-1)]) for j in range(2*N-1)]))
Explanation:
We will work in this 2*N-1x2*N-1 grid, for now with zeros:
[[0 for i in range(2*N-1)] for j in range(2*N-1)]
Then, we want the formating, so we convert things to string and join them:
print('\n'.join([''.join([str(0) for i in range(2*N-1)]) for j in range(2*N-1)]))
Ok, we have zeros, but we want your number matrix, so we apply this formula for the matrix with i and j indexes max(max(N-i,N-j),max(i-N+2,j-N+2)):
print('\n'.join([''.join([str(max(max(N-i,N-j),max(i-N+2,j-N+2))) for i in range(2*N-1)]) for j in range(2*N-1)]))
Now that we have the numbers matrix, let's apply this transformation: chr(64+k) => capital letter of the alphabet, starting from zero, because 'A' is ascii code 64, 'B' is ascii code 65, and so on...
print('\n'.join([''.join([chr(64+max(max(N-i,N-j),max(i-N+2,j-N+2))) for i in range(2*N-1)]) for j in range(2*N-1)]))
There we have it.
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
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))