Read k matrices size nxm from stdin in Python - python

I need to read k matrices size nxm from stdin in Python.
In the first line there must be the number of matrices (k), and then - k descriptions of matrices: in the first line 2 integer numbers for size (n and m) devided by space, then the matrix.
Here's an example:
2
2 3
4 5 6
3 1 7
4 4
5 3 4 5
6 5 1 4
3 9 1 4
8 5 4 3
Could you please tell me how I can do this?
I could have done this only without considering m (for 1 matrix):
n = int(input())
a = []
for i in range(n):
a.append([int(j) for j in input().split()])
I have found some similar questions but stdin is not used (e.g. reading from file is used) or the size of string in matrix is not set.

You are on a right way. try to break it in simple steps. Basically a n X m matrix is n rows and each row would have m elements (pretty obvious). what if we have n=1 then we have a line in which there would be m element. to take such input we would just
matrix = input().split() #read the input
matrix = [ int(j) for j in matrix] #matrix is now 1 x m list
or simplify this
matrix = [ int(j) for j in input().split() ]
now suppose we have n rows, that means we have to do this n times which is simply looping n times ,
matrix = [ [ int(j) for j in input().split() ] for i in n ]
a more pythonic way is using map,
matrix= [ list( map(int, input().split() ) ) for i in range(n) ]

Related

How to take Different multi line inputs?

The other day, for the first time I participated in a coding contest and I faced an issue with taking inputs. There were 4 sample cases and each sample case had n test cases. So each sample case was in the format:
First line denotes number of test cases
Second line denotes number of elements in array A
Third line denotes elements of array A
Fourth line denotes elements of array B
To make more sense, the input was (say),
3 // Number of test cases
5 // Size of array A
2 4 3 7 9 // array A
14 21 11 // array B
3 // Size of array A
6 7 2 // array A
9 8 // array B
4 // Size of array A
5 2 6 7 // array A
12 17 // array B
The solution that I tried was
t = int(input()) # Number of sample cases
for i in t:
n = int(input()) # Size of array A
arr_A = [int(x) for x in input().split()]
arr_B = [int(x) for x in input().split()]
# Statements...
When I was running the code I was getting EOF error or some error. To test what was causing the error I reduced the aforementioned sample case to
1 // Number of test cases
5 // Size of array A
2 4 3 7 9 // array A
14 21 11 // array B
And with this input the code was running fine.
I will truly appreciate if you tell me possible ways of taking such inputs?
In your code, for i in t should be modified to for i in range(t) since we need to iterate up to a certain number.
This is the approach I usually use when it comes to taking inputs.
t = int(input())
while t > 0:
n = int(input())
arrA = list(map(int, input().split()))
arrB = list(map(int, input().split()))
t-=1

How to use a loop in python to return elements of an array into a given set?

For each index of a sorted array i = 1,...,N in this new array I want to find all indexes j such that xj is in the set (xi-5, xi+5).
x= np.array([1,2,2,3,4,6,7,9])
n=len(x)
for i in range(n):
for j in range(n):
if x[i] - 5 < x[j] and x[i] + 5 > x[j]:
print(j)
So for this array example I gave, when i=0, x=1. So it should return [1,2,3,4] because they are all in (x_1-5, x_1+5). Then when i=1, x=2, and should return [0,2,3,4,5] and so on. I should get N arrays.
But, the output gives me
0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 1 2 3 4 5 6 7 3 4 5 6 7 5 6 7
I don't know how I can implement this and I think the problem is for j in x since it is the same as the first loop. In my eyes, it says for every i, if any xj is in (xi-5,xi+5) then return the jth element. But, I want to return N sets.
Writing your indexes that way is probably what is confusing you.
If you want to access an index that is n-2 then you have to index it that way.
What you are doing is accessing the nth index of your list and then subtracting or adding 2 from the value that you accessed.
x[i]
returns whatever value is at position i in the list.
x[i-2]
will return whatever value is at position i-2.
Also you will need to account for the fact that subtracting any number from your index variable will cause your resulting index to be out of bounds if the resulting index is greater than the length of the list - 1 or less than 0.
If you are looking for duplicates the best way is to sort first then compare neighbors.
for i in x:
if x[i] == x[i+1]:
print i;
Subsetting is done like this: x[i-2:i+2]
So to divide into n sets of 2 elements you would:
n=2
for i in x:
if i+n < len(x):
return x[i:i+n];
To divide into n sets of equal number of elements you would:
n = // Some arbitrary number.
j = int(len(x) / n);
for i in x:
if i+j < len(x):
return x[i:i+j];

Kickstart Round C 2020 Countdown Problem - finding number of contiguous subarray

Edit - The output didn't have a space before the colon. But after changing that, instead of wrong answer, it's saying runtime error. Even the sample input tests ran successfully. What could possible be wrong?
Problem
Avery has an array of N positive integers. The i-th integer of the array is Ai.
A contiguous subarray is an m-countdown if it is of length m and contains the integers m, m-1, m-2, ..., 2, 1 in that order. For example, [3, 2, 1] is a 3-countdown.
Can you help Avery count the number of K-countdowns in her array?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integers N and K. The second line contains N integers. The i-th integer is Ai.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of K-countdowns in her array.
Limits
Time limit: 20 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
2 ≤ K ≤ N.
1 ≤ Ai ≤ 2 × 105, for all i.
Test set 1
2 ≤ N ≤ 1000.
Test set 2
2 ≤ N ≤ 2 × 105 for at most 10 test cases.
For the remaining cases, 2 ≤ N ≤ 1000.
Sample
Input
3
12 3
1 2 3 7 9 3 2 1 8 3 2 1
4 2
101 100 99 98
9 6
100 7 6 5 4 3 2 1 100
Output
Case #1: 2
Case #2: 0
Case #3: 1
T = int(input())
res = []
for i in range(T):
N, K = map(int, input().split(' '))
ai = list(map(int, input().split(' ')))
y=0
count=0
for m in range(len(ai)):
count=0
if(ai[m]==K):
if(len(ai)>=m+K-1):
for j in reversed(range(1, K)):
if(ai[m+K-j]==j):
count=count+1
if(count==K-1):
y=y+1
else:
break
else:
continue
res.append("Case #"+str(i+1)+" : "+str(y))
for g in range(len(res)):
print(res[g])
You can use a two-pointer approach like take two variables i and j and initialize both with 0
Keeping i fixed increment j if the required condition is met i.e.
while(a[k+1]-a[k]==1):
j++
k++
wherever condition fails, calculate j-i. If at all j-i==m then increment your counter say cnt and then put i=j and repeat until the end of array

How to input element in 2d array

Like below C++ Code, how could I use Python to input elements in 2d array? Please, help in writing the same program in Python3.
int main()
{
int s = 3;
int a[s][s];
cout<<"Enter 9 Element in Square Matrix";
for(int i =0;i<s;i++)
{
for(int j =0; j<s;j++)
{
cin>>a[i][j];
}
}
cout<<"You Entered";
for(int i =0;i<s;i++)
{
for(int j =0; j<s;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
Output:
Enter 9 Elements in Square Matrix
1
2
3
4
5
6
7
8
9
You Entered:
1 2 3
4 5 6
7 8 9
If there is a mistake in the program, please don't try to correct it.
Thank you.
Am gonna use list to store the 2D array here. There are many other structures you can use for storing a 2D array, but for basic needs, this will suffice.
n=int(input("Enter N for N x N matrix : ")) #3 here
l=[] #use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
for i in range(n):
row_list=[] #temporary list to store the row
for j in range(n):
row_list.append(int(input())) #add the input to row list
l.append(row_list) #add the row to the list
print(l)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
for i in range(n):
for j in range(n):
print(l[i][j], end=" ")
print() #new line
'''
1 2 3
4 5 6
7 8 9
'''
s = 3
a = [x[:] for x in [[0] * s] * s]
print("Enter 9 Element in Square Matrix")
for i in range(0, s):
for j in range(0, s):
a[i][j] = input()
print("You Entered")
for i in range(0, s):
line = ''
for j in range(0, s):
line += a[i][j] + ' '
print(line)
If you are not familiar with python, you should create a file called, for example, matrix.py and then add the following content:
matrix_size = 3
matrix = []
print("Enter {} Elements in Square Matrix:".format(matrix_size))
for i in range(0, matrix_size):
row = []
for j in range(0, matrix_size):
row.append(input())
matrix.append(row)
print("You entered:")
for i in range(0, matrix_size):
print(" ".join(matrix[i]))
After saving the file, you can execute this file this way:
python3 matrix.py
Here is a sample output:
[martin#M7 tmp]$ python3 matrix.py
Enter 3 Elements in Square Matrix:
1
2
3
1
2
3
7
5
4
You entered:
1 2 3
1 2 3
7 5 4
Say you want to create a 3*3 matrix:
Initialize the matrix as follows:
matrix = [x[:] for x in [[0] * 0] * 0]
Then take the matrix elements as input from the user:
for i in range(0,3):
row_list = []
for j in range(0,3):
row_list.append(int(input()))
matrix.append(row_list)

Python code for converting two mode matrix data into one-mode

Being a novice on Python, I am wondering if there is any way possible I can convert two mode matrix data into one mode using Python code.
This is to create a data for social network analysis, and I am looking for a way to use Pandas and Python to create such a script.
Provided I have two mode data llke this,
workshop1 workshop2 workshop3 workshop4
A 1 0 1 1
B 0 1 1 0
C 1 1 1 0
D 0 0 0 1
I need to convert that into one mode matrix like this.
A B C D
A 4 1 2 1
B 1 4 2 0
C 2 2 4 0
D 1 0 0 4
A,B,C,D are names of persons registered for workshops, "1" means the specific person signed up for the workshop.
One-mode matrix data indicate how many times they are supposed to meet each other at workshops. For example, A and C are expected to meet two times at workshop 1 and workshop3.
Thank you any advise or help in advance!
NumPy solution:
According to this tutorial you can simply multiply the matrix with it's transpose. Using the NumPy functions dot() and transpose() (or the short form T) you end up with the following code:
import numpy as np
M = np.array([
[1,0,1,1],
[0,1,1,0],
[1,1,1,0],
[0,0,0,1]])
print M.dot(M.T)
Output:
[[3 1 2 1]
[1 2 2 0]
[2 2 3 0]
[1 0 0 1]]
Only the diagonals are not 4 as you requested. In contrast they contain the number of workshops a person attended. You can easily fix that with np.fill_diagonal(A, 4) with A being the one-mode matrix.
No-NumPy solution:
In case you don't want to use NumPy, you can adapt a standard matrix multiplication to the special case of "R = M*M^T":
m = len(M)
n = len(M[0])
R = [[0 for i in range(m)] for j in range(m)]
for i in range(m):
for j in range(m):
for k in range(n):
R[i][j] += M[i][k] * M[j][k]
Or the corresponding one-liner with 3 indices i, j and k:
R = [[sum(M[i][k] * M[j][k] for k in range(len(M[0]))) for i in range(len(M))] for j in range(len(M))]
Or directly iterating over rows of M:
R = [[sum(a * b for a, b in zip(A, B)) for B in M] for A in M]

Categories