How to insert value to matrix by user input?
I've got some code like this.
n,m = raw_input().split(' ')
matrix = [[0 for x in range(int(n))] for y in range(int(m))]
How it should looks like:
user input :
2 2 #dementions of matrix
1 2 #matrix[1][1] = 1; #matrix[2][1] = 2
3 4 #matrix[2][1] = 3; #matrix[2][2] = 4
output :
1 2 #matrix[1][1] = 1; #matrix[2][1] = 2
3 4 #matrix[2][1] = 3; #matrix[2][2] = 4
Here is the code for taking matrix input in python:
n,m=map(int,raw_input().split())
a=n*[m*[0]]
j=0
for i in range (0,n):
a[i][j]=map(int,raw_input().split())
j+=1
j=0
for i in range (0,n):
print a[i][j]
j+=1
Related
how can i print the matrix[i][j]?
from array import *
class Sudoku :
matrix = []
x = -1
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a)
except:
matrix.append(x)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
error is :
print(matrix[i][j])
TypeError: 'int' object is not subscriptable
You can use this code if you want to complete the code with minimum number of lines but it sure is a bit complex.
m,n=input("Enter num of rows and columns:").split()
matrix=[[int(input()) for y in range(int(n))]for x in range(int(m))]
[[[print(matrix[i][j], end=" ") for j in range(int(n))] and print(" ") ]for i in range(int(m))]
The output looks like this:
Enter num of rows and columns: 3 3
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9
from array import *
class Sudoku:
matrix = []
x = -1 # <--- 4
for i in range(0, 10):
a = []
for j in range(0, 10):
try:
a.append(int(input(f"Enter matrix{[i]}{[j]} element: ")))
if (isinstance(a, int)) == True :
matrix.append(a) # <--- 11
except: # <--- 12
matrix.append(x) # <--- 13
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j]) # <--- 16
Let's look at the code. If except at L12 is catched, x, which is -1 (L4) is appended. So at L16, when matrix[i] evaluates to -1, -1[j] is an error.
There's also another problem -- L11 will never be executed, because a is always a list, not int.
matrix = [] is declaring matrix to be a list. But you are thinking of the matrix as having i,j locations like in math.
You have two options:
Option1: Map the list to a matrix
If you have a 3x3 matrix you have 9 locations, so
matrix = [0, 1, 2, 3, 4, 5, 6, 7, 8] is equivalent to
0 1 2
matrix = 3 4 5
6 7 8
so if wanted to print out this matrix you have to do some math to access the elements
for i in range(3): # i = 0, 1, 2
for j in range(3): # j = 0, 1, 2
print(matrix[3*i + j], end=" ")
print("")
Option2: Make matrix be a nested list
have matrix becomes a list of row, and each row is a list of elements
matrix = []
x = -1
for i in range(0, 10):
row = []
for j in range(0, 10):
while True:
x = int(input(f"Enter matrix[{i}][{j}]} element: "))
if (isinstance(x, int)) == True :
row.append(x)
break;
matrix.append(row)
for i in range(0, 10):
for j in range(0, 10):
print(matrix[i][j])
Thanks for the help in advance.
I compare 2 variables which hold numbers with the operation !=
the program takes input like this
4
1 2 3 4
Then the program should return the highest product exluding a square product. In this case the result should be 12(4x3) not 16(4x4) but it is incorrectly returning 16.
The code is here
def max_pairwise_product():
n = int(input())
a = input().split()
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != integer1:
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
This is because your comparing an int to a str. I have edited your code minimally to fix this issue, but you have better to edit your list input before hand.
def max_pairwise_product():
n = int(input())
a = input().split() #If I were you I would do: a = [int(x) for x in input().split()]
maxno = 0
for integer1 in a:
product = int(integer1) * n
if n != int(integer1): #This is were I have changed
if product > maxno:
maxno = product
return maxno
print(max_pairwise_product())
You compare string vs. integer which is always False:
for integer1 in a: # integer1 is a string
product = int(integer1) * n
if n != integer1: # n is a number
Fix:
def max_pairwise_product():
_ = input() # not used
a = "1 2 3 4".split() # input() removed and fixed input given
a = sorted(set(map(int,a))) # convert all to intergers and sort unique numbers
maxno = 0
for idx,number in enumerate(a):
for number2 in a[idx+1:]:
maxno = max( maxno, number*number2 )
return maxno
print(max_pairwise_product())
Output:
12
The loops are optimized leveraging the fact that they numbers are sorted and unique - thats why the second loop can be shorter - no need to recompute already computed results.
Its good if you get inputs like '1 1 1 1 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6' because it will only compute for '1 2 3 4 5 6' and never compute any paring twice.
I am trying to print the following pattern in python but am not getting the desired output :
0
2 2
4 4 4
6 6 6 6
I have already used the following code but am not getting the desired output
n = int (input("Enter number : "))
for i in range (n):
print (i *2 )
Try this:
n = int (input("Enter number : "))
for i in range (n):
print (' '.join([str(i * 2) for _ in range(i + 1)]) )
You need to print the number i+1 times.
for i in range (n):
for _ in range(i+1):
print (i * 2," ", end='') # print without newlines
print() # end the line
Following simple code could help:
n = int (input("Enter number : "))
j = 1
k = 0
for i in range(n):
s = str(k)+' '
print(s*j)
j += 1
k += 2
if n = 4, then it would print the following :
0
2 2
4 4 4
6 6 6 6
n = int (input("Enter number : "))
count = 1
for i in range (n):
res = str(i*2) + " "
print (res * (i+1))
print n
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)
I use the for loop to input the n words
n = int(input(""))
for i in range(n):
a = input("")
print(a)
when I input:
3
1
1
1
2
It allow me to input the n+1 words
And the n+1 word can not be output
I just want to output n words then equal with the syntax in C:
int a = 0;
for(int i=0; i<n; i++)
scanf("%d",&a);
[Update]
Actually it is a problem with Pycharm. And I don't know why.
In terminal,the code can work.
So,plz not downvote....
I don't understand why this isn't working for you. Try this modified version that makes it clearer what is happening:
n = int(input("Enter number of values: "))
for i in range(n):
a = input("Enter value {} ".format(i+1))
print("Value {0} was {1}".format(i+1, a))
The ouput from this was:
Enter number of values: 3
Enter value 1 1
Value 1 was 1
Enter value 2 1
Value 2 was 1
Enter value 3 2
Value 3 was 2
It ran exactly 3 times when I tried it.
If you want to make it more explicit what you're doing you could set it to for i in range(0,n): but that won't really change anything.
The loop for i in range(n): will run from 0 to n-1.
So if you put in 3 it, it will generate 3 runs, with the values of i being 0, 1, 2.
n = int( input( "Enter the number of runs: " ) )
for item in range( 0, n ):
a = input( "\tPlease Input value for index %d: "%item )
print( a )
It generated the output:
Enter the number of runs: 3
Please Input value for index 0: 1
1
Please Input value for index 1: 1
1
Please Input value for index 2: 1
1
I think you are confusing with the output printed by the loop.
If you enter 3 in the first n = int(input(""))" the loop will go from 0 to 2 (inclusive).
In every loop you ask for a new value of a and print it. So, after the first loop, you input 1 and it outputs 1 (because it prints it). In the second loop you input another 1 and it prints it. Finally you input a 2 and it also prints it.
First loop:
input: 1
output: 1
Second loop:
input: 1
output: 1
Third loop:
input: 2
output: 2
That's why if I run the following
>>> n = int(input(""))
3
>>> for i in range(n):
... a = input("")
... print a
...
1
1
2
2
3
3
I get 6 numbers (inputs and outputs). You can see this more clearly with the following example:
>>> n = int(input("Input: "))
Input: 3
>>> for i in range(n):
... a = input("Input: ")
... print "Output: " + str(a)
...
Input: 1
Output: 1
Input: 2
Output: 2
Input: 3
Output: 3