Issue with Updating elements in a 2D Matrix - python

n = 5
k = 6
matrix = [[j for i in range(n)] for j in range(k)]
for element in matrix[3]:
print(element)
element = 100
print(matrix)
I expect to see one row in my matrix to be all 100 at the end, but the values are all still initial values, why is this happening?

When you run:
for element in matrix[3]:
element = 100
all you're doing is changing the element inside the for loop. When another round of the for loop starts, element is changed back to what it should be, i.e.: the next element in the matrix. You can think of element as a temporary variable that changes every run of the loop.
More importantly, 'element' is now separate from the matrix. Changing 'element' will not change the matrix. You need to directly call on the matrix element you want to change and assign it whatever value you want to set it to. The proper way to do this would be to do:
for i in range(len(matrix[3])):
matrix[3][i] = 100
Check the code below for what the right code should look like.
n = 5
k = 6
matrix = [[j for i in range(n)] for j in range(k)]
for i in range(len(matrix[3])):
matrix[3][i] = 100
print(matrix)

Related

how to take 2d list from user in 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.

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.

Minimum of 4th Element in NxNx4 list (Python)

Hi I've been reading up on finding the minimum of a multidimensional list, but if I have an N x N x 4 list, how do I get the minimum between every single 4th element? All other examples have been for a small example list using real indices. I suppose I'll be needing to define indices in terms of N....
[[[0,1,2,3],[0,1,2,3],...N],[[0,1,2,3],[0,1,2,3],...N].....N]
And then there's retrieving their indices.
I don't know what to try.
If anyone's interested in the actual piece of code:
relative = [[[[100] for k in range(5)] for j in range(N)] for i in range(N)]
What the following does is fill in the 4th element with times satisfying the mathematical equations. The 0th, 1st, 2nd and 3rd elements of relative have positions and velocities. The 4th spot is for the time taken for the i and jth particles to collide (redundant values such as i-i or j-i are filled with the value 100 (because it's big enough for the min function not to retrieve it). I need the shortest collision time (hence the 4th element comparisons)
def time(relative):
i = 0
t = 0
while i<N:
j = i+1
while j<N and i<N:
rv = relative[i][j][0]*relative[i][j][2]+relative[i][j][1]*relative[i][j][3] #Dot product of r and v
if rv<0:
rsquared = (relative[i][j][0])**2+(relative[i][j][1])**2
vsquared = (relative[i][j][2])**2+(relative[i][j][3])**2
det = (rv)**2-vsquared*(rsquared-diameter**2)
if det<0:
t = 100 #For negative times, assign an arbitrarily large number to make sure min() wont pick it up.
elif det == 0:
t = -rv/vsquared
elif det>0:
t1 = (-rv+sqrt((rv)**2-vsquared*(rsquared-diameter**2)))/(vsquared)
t2 = (-rv-sqrt((rv)**2-vsquared*(rsquared-diameter**2)))/(vsquared)
if t1-t2>0:
t = t2
elif t1-t2<0:
t = t1
elif rv>=0:
t = 100
relative[i][j][4]=t #Put the times inside the relative list for element ij.
j = j+1
i = i+1
return relative
I've tried:
t_fin = min(relative[i in range(0,N-1)][j in range(0,N-1)][4])
Which compiles but always returns 100 even thought I've checked it isnt the smallest element.
If you want the min of 4th element of NxNx4 list,
min([x[3] for lev1 in relative for x in lev1])

Fill a matrix with an array

I have some code of which I obtain an array of different values within a double for loop. I assign it to a list test
and I want to set them one by one on this matrix of 8 x 8
I have tried:
for i in range(8):
for j in range(8):
matrixc[i][j] = testi[i]
I want to have a different value on each tuple. How can I advance through the list on each iteration?
Is this what you are looking for?
for i in range(8):
for j in range(8):
matrixc[i][j] = testi[i*8 + j]
Alternatively:
for index, element in enumerate(testi):
matrixc[index / 8][index % 8] = element
If you're pulling from a linear array then you could access it using array[i*8 + j] instead of array[i]

select first n items of a list without using a loop.

I know I can do this with a loop but I was wondering if there was a neater solution?
I have a list, which I want to select the first n items and place them in another list.
What I want to do is something like (pseudo code)
n = 3
x = [1,2,3,4,5,6,7,8,9,0]
y = copy n from x
print(y)
>>> [1,2,3]
Thanks
You can use slicing like this
y = x[:n]
print(y)
When you say x[:n], it means that, get all the elements till index n (but not including the element at index n).

Categories

Resources