how to take 2d list from user in python? - python

I want that user give input like this
[[3,4,5],[7,2,1]]
and it will create a 2d array automatically and store in a. so when print(a) will given it returns
a=[[3,4,5],[7,2,1]]
where type(a[0][0]) i mean all elements inside a will be int. How can I do it?

Input:
2 // no.of rows
3 // no.of columns
1 2 3
4 5 6
Output:
[[1,2,3],[4,5,6]]
Solution:
r = int(input())
c = int(input())
a = [list(map(int,input().split())) for _ in range(r)]
print(a)
The variable c isn't used in the code, so you can simply get it as a string and also ignore the assignment using input()
Line 3 involves List Comprehension (documentation).

n = int(input())
m = int(input())
input_list = []
for i in range(n):
list1 = []
for j in range(m):
z = int(input())
list1.append(z)
input_list.append(list1)
print(input_list)
Okay so we take the size of the 2-d array from the user in n and m resp.
We create an empty list named as input_list.
Now we run a loop for n times so this will be the number of rows in the 2-d array.
for every row we create a list named as list1. Run a loop to take inputs from the user on the elements in the row.
Then we append the newly created row (list1) in the input_list.This action is performed for all the rows.
And when the execution finishes we get the input_list as a 2-d array.

Related

I am getting error in code in taking input and append it to array

You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.
Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations. Note: For each cut operation, you have to recalculate the length of smallest sticks (excluding zero-length sticks).
Input
The first line contains a single integer N.
The next line contains N integers separated by space, where each integer represents the length of the ith stick.
6
5 4 4 2 2 8
Output
For each operation, print the number of sticks that are cut, on separate lines.
6
4
2
1
Explanation
import array as arr
n = int(input())
a = arr.array('i',[1002])
for i in range(n):
c = [int(x) for x in input().split()]
a.append(c)
t=n
for i in range(0,1001):
if a[i] > 0:
print(t)
t=t-a[i]
You can't append a list to an integer array. If you want to merge two arrays you can use the extend method.
a.extend(c)
if a is list then below all satisfies but here a is array so we cant append list with array
a = [1,2,3] # a is a list
c = [4] # c is list
it won't give you correct result in any case
print(a.append(c)) # if we do a.append(c) result is like a = [1,2,3,[4]]
gives you correct result in any case
print(a.extend(c)) # if we do a.extend(c) result is like a = [1,2,3,4]
satisfies if "a" is list and "c" is list or "a" is array and "c" is also an array
a += c # a += c result is same as a.extend(c)
print(a) # a = [1,2,3,4]

How to print two input lists within a list in separate lines without using NumPy?

I have a program which adds two matrices (lists) and prints the sum.
First, the program asks to specify the number of rows and columns as dimensions of the matrices.
Then it asks to enter the specified number of digits as rows and columns, as follows:
dimension: 2 3
numbers in the list: 1 2 3
numbers in the list: 4 5 6
dimension: 2 3
numbers in the list: 7 8 9
numbers in the list: 7 8 9
I am trying to print the sum of two input lists (matrices) exactly in the following format - two rows in separate lines, three columns, without square brackets:
8 10 12
11 13 15
but end up with this output:
[8, 11, 10, 13, 12, 15]
I have tried several other solutions suggested in other similar posts but haven't been able to make them work.
Without using NumPy, map() or lambda functions, how can I get the desired output?
# input the number of rows and columns (dimensions of the matrix)
rows_cols = input().split()
# save the dimensions as integers in a list
matrix_dim = [int(i) for i in rows_cols]
numbers = 0
matrix_A = []
matrix_B = []
matrices = []
# take the row times the input for the rows of matrix_A
for _ in range(matrix_dim[0]):
numbers = input().split()
matrix_A.append([int(i) for i in numbers])
rows_cols = input().split()
matrix_dim = [int(i) for i in rows_cols]
# take the row times the input for the rows of matrix_B
for _ in range(matrix_dim[0]):
numbers = input().split()
matrix_B.append([int(i) for i in numbers])
# add matrices matrix_A and matrix_B
matrices = [matrix_A[i][k] + matrix_B[i][k] for k in range(len(matrix_A[0])) for i in range(len(matrix_A))]
# print ERROR if the number of columns entered exceed the input number for columns
if len(numbers) != matrix_dim[1]:
print("ERROR")
else:
print(matrices)
The easy way to do this will be to start with the fix suggested by nathan:
matrices = [[matrix_A[i][k] + matrix_B[i][k] for k in range(len(Matrix_A[0]))] for i in range(len(matrix_A))]
That gives you a 2-d array rather than a 1-d array
[[a, b, c], [d, e, f]]
but now we need to print it nicely. Here's a function to turn the matrix into a pretty string:
def prettyString(matrix):
result = ''
for row in matrix:
for value in row:
result += value
result += '\n'
return result
Finally, in your code, you can use the new function:
print(prettyString(matrices))
All you have to do is change how you sum the matrices:
matrices = [[matrix_A[i][k] + matrix_B[i][k] for k in range(len(Matrix_A[0]))] for i in range(len(matrix_A))]
Then to print:
for row in matrices:
# print(row)
print(" ".join(row))
Or
from pprint import pprint
pprint(matrices)
Try this -
First calculate the sum list of lists as output, then join the elements of sublist with spaces and join those sublists strings with \n (newline character). When you then print it, it will print it out one sublist at a time.
output = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
print_out = '\n'.join([' '.join([str(j) for j in i]) for i in output])
print(print_out)
#sample output
1 2 3
4 5 6
zip function can be helpful when you try to combine lists of lists. This will work for any n x m matrices.
m1 = [
[1,2,3],
[4,5,6]]
m2 = [
[7,8,9],
[7,8,9]]
for row1,row2 in zip(m1,m2):
print(*[el1+el2 for el1,el2 in zip(row1,row2)])
Output:
8 10 12
11 13 15

Python randint() repeats numbers - seed is not the problem?

i do learn Python for scientific working. At the moment i try to generate a 10x10 random Matrix with binary entries: 0 and 1. I already got a solution with numpy BUT im interested of what is the error in my own solution.
The Idea is to Access every entry of my Matrix seperately and assign a value to it by calling random.randint(0, 1 ) within two while loops. In Advance i define a dummy 10x10 Matrix called "World" and reassign ist values it in the loop. The Code Looks how follows:
import random
World=list(10*[10*[0]]) #this is my dummy matrix
i=0
j=0
while i <= 9:
while j <= 9:
World[i][j]=random.randint(0, 1) #here i want to Access a specific element of my dummy Matrix and "overwrite" it
if j == 9:
j=0 #if the counter "j" reaches 9 - the last element - it shall assign j=0 and leave the innermost while loop by "break"
break
j=j+1
i=i+1
for x in World:
print(*x)
The Problem with the Output should be obvious:
columns are equal
I am hopefully u understand what was my Intention here and can help me fix my code. I tried many many Things but i did not fix this.
I already found a 2-line short solution which i will use in my final Code but i want to run this also on my own because i am convinced this could work also well.
Many Thanks in Advance.
- Wendel
Your error is in the creation of the list.
NOTE:
[0] * m returns just a reference to a list of m zeros, but not a list.
The subsequent repeating of this element creates a list of n items
that all reference to the same list (just as well as the operation b =
a for lists does not create the new list), so all rows in the
resulting list are actually the same string.
import random
#World=list(10*[10*[0]]) #this is my dummy matrix
n = 10
World= [0] * n
for i in range(n):
World[i] = [0] * n
i=0
j=0
while i <= 9:
while j <= 9:
World[i][j]=random.randint(0, 1) #here i want to Access a specific element of my dummy Matrix and "overwrite" it
if j == 9:
j=0 #if the counter "j" reaches 9 - the last element - it shall assign j=0 and leave the innermost while loop by "break"
break
j=j+1
i=i+1
for x in World:
print(*x)
Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros.
The obvious solution appears to be wrong:
a = [[0] * m] * n
This can be easily seen if you set the value of a[0][0] to 5, and then print the value of a[1][0] — it will also be equal to 5. The reason is, [0] * m returns just a reference to a list of m zeros, but not a list. The subsequent repeating of this element creates a list of n items that all reference to the same list (just as well as the operation b = a for lists does not create the new list), so all rows in the resulting list are actually the same string.
n = 3
m = 4
a = [[0] * m] * n
a[0][0] = 5
print(a[1][0])
A possible way: you can create a list of n elements (say, of n zeros) and then make each of the elements a link to another one-dimensional list of m elements:
n = 3
m = 4
a = [0] * n
for i in range(n):
a[i] = [0] * m
Another (but similar) way: create an empty list and then append a new element to it n times (this element should be a list of length m):
n = 3
m = 4
a = []
for i in range(n):
a.append([0] * m)
But the easiest way is to use generator, creating a list of n elements, each of which is a list of m zeros:
n = 3
m = 4
a = [[0] * m for i in range(n)]
In this case each element is created independently from the others. The list [0] * m is n times consructed as the new one, and no copying of references occurs.

Mistake in Python code

There is an array of integers. There are also disjoint sets, A and B, each containing integers. You like all the integers in set A and dislike all the integers in set B. Your initial happiness is 0. For each integer in the array, if i in A, you add 1 to your happiness. If i in B, you add -1 to your happiness. Otherwise, your happiness does not change. Output your final happiness at the end.
Input Format
The first line contains integers n and m separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A and B respectively.
Output Format
Output a single integer, your total happiness.
Sample Input
3 2
1 5 3
3 1
5 7
Sample Output
1
Can someone please explain what is wrong with this solution? It passes some test, but fails on others.
input()
array = set(input().split())
set1 = set(input().split())
set2 = set(input().split())
res = len(set1 & array) - len(set2 & array)
print(res)
The problem is that you're transforming your inputs to sets, which in turn removes the duplicates. If you have repeated values in your input, with the set you're only adding/substracting 1 to the resulting happiness. If that's correct, your code is fine. If not, then you should work with lists rather than sets.
The code could be something like this:
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# Now we use some list comprehension to get the happiness result
res = sum([1 for elem in array if elem in list1]) - sum([1 for elem in array if elem in list2])
The first sum accumulates the positive points, and the second one the negatives. It works with multiple occurences, adding/substracting one point per each.
EDIT
A more clear approach, to understand the for loop
# The first part should stay the same, without the set() call on array
input()
array = input().split()
list1 = set(input().split())
list2 = set(input().split())
# We create a variable res which will store the resulting happiness, initially 0
res = 0
# Now we iterate through the elements in array and check wheter they should add or substract
for elem in array:
# If the element is in list1, we add 1 to res
if elem in list1:
res += 1
# If the element is in list2, we substract 1 from res
elif elem in list2:
res -= 1
I took the inputs for list A and B and as a general list. I wanted to obtain happiness in 1 line using list comprehension as below. After I merged print and "happiness =" , in one line. Apparently, this is the solution to make the code faster.
input()
my_array = input().split()
listA=list(input().split())
listB=list(input().split())
print (sum(1 for data in my_array if data in listA)+sum(-1 for data in my_array if data in listB))

how to construct two dimensional lists using the example ive given

I am stuck in question relating to the two dimension list, the questions are Write a program that constructs a two dimensional list containing 5 lists each containing 5 elements. The value of the ith element in the jth list should be j×5+i using the code.
Adapt the program from the previous question so that it asks the user for two dimensions, then constructs a two dimensional list with the specified dimensions with the values as described in the previous questions.
As I am a new to programming please can you help me.
#create a variable called a of type list
a = []
for I in range(5):
#append an empty list to a
a.append([])
for j in range (5):
#append 0 to the ith list of a
a[I].append(0)
#print a
print(a)
This should do the work
x = input('Type a value for the number of lines: ')
y = input('Type a value for the number of columns: ')
#create a variable called a of type list
a = []
for i in range(x):
#append an empty list to a
a.append([])
for j in range (y):
#append 0 to the ith list of a
a[i].append(j*5+i)
#print a
print(a)
I think list comprehension wins here:
[[j*5+i for j in range(5)] for i in range(5)]

Categories

Resources