Replacing list in list of list , gives only zeros - python-3.x

I have a matrice (list of list) say a and I want to normalize each "row" such that each element corresponds to the fraction of the corresponding row, i.e [p/sum(p) for p in row].
I have the following code
a_norm[:] = a
for i,row in enumerate(a_norm):
b = [p/sum(row) for p in row]
print(b)
a_norm[i] = b
the rows being printed (print(b)) are completely fine but a_norm consists of purely zeros for some reason.
EDIT: Adding an example.
a=np.array([[1,2,3], [20,22,13]]) should give a_norm=[[0.16,0.33,0.5],[0.36,0.4,0.24]]

try this one:
a_norm = [[i / sum(row) for i in row] for row in a]

Mistake you did in making list copy.
use a_norm = a[:] instead of a_norm[:] = a
You can try:
a_norm = a[:]
for i, row in enumerate(a_norm):
b = [p/sum(row) for p in row]
print(b)
a_norm[i] = b
print(a_norm)

Related

Get corresponding element from maximum of element wise 2d array

I have four 2d arrays.
A = [[1,6], [3,5]]
A' = [[11,22], [33,44]] //each index value is related to corresponding index at A
similarly
B = [[5,2],[2,3]]
B' = [[55,66],[77,88]]
output
o/p = [[5,6], [3,5]]
o/p' = [[55,22],[33,44]] // how to get this output
I want to get element wise maximum from A and B, but I want to get the corresponding element
from A' and B'.
Doing a n^2 iteration is taking a lot of time.
numpy.maximum(A,B,A) can get me maximum value but how can I get corresponding elements from A' and B'.
You could do this:
# Defining the arrays
A = np.array([[1,6], [3,5]])
A2 = np.array([[11,22], [33,44]])
B = np.array([[5,2],[2,3]])
B2 = np.array([[55,66],[77,88]])
# Get maximum of A and B. Do not do np.maximum(A, B, A), as this overwrites A.
C = np.maximum(A, B)
# Get indices where C = A and C = B.
A_indices = np.where(C == A)
B_indices = np.where(C == B)
# Get corresponding A2 and B2 values.
C2 = np.copy(C)
C2[A_indices] = A2[A_indices]
C2[B_indices] = B2[B_indices]
C2 now has the values you want. Let me know if you have any questions.

How to write a cycle for creating numpy arrays?

How to write this in cycle, please?
k1 = np.empty(np.shape(u))
k2 = np.empty(np.shape(u))
k3 = np.empty(np.shape(u))
k4 = np.empty(np.shape(u))
I tried:
k = [k1, k2, k3, k4]
for i in k:
i = np.empty(np.shape(u))
k.append(i)
You can simply use list comprehension to create an arbitrary number of empty numpy arrays
num = 10
result = [np.empty(np.shape(u)) for _ in range(num)]
It is not a good practice to do this, so I would recommend using lists or dictionaries but here's the code to achieve what you asked for-
for x in range(0, n): #Replace n with the value you need
globals()['k%s' % x] = np.empty(np.shape(u))
and then for example:
print(k1)
But again this is a bad practice, use dictionaries instead

python finding the greatest common divisor of two numbers program

I am a new Python learner. I am trying to finding the greatest common divisor of two numbers (a =1071 and b = 462 for example). I have written two programs for this. the first one is working but the second one gives the wrong answer. what is the problem with my program??
# first program (works)
a, b = 1071, 462
while b:
a, b = b, a % b
print(a)
# second program (doesn't work truly)
a = 1071
b = 462
while b:
a = b
b = a % b
print(a)
Explanation:
Yes, HSK is right. In the 2nd loop:
while b:
a = b
b = a % b
print(a)
First a is changed to b and then what you do is b = b% b. But here:
a, b = b, a % b
it is executed as one-line so a is still a.
Solution:
So just add a third variable:
a = 1071
b = 462
while b:
c = a
a = b
b = c % b
print(c)
One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that it is executed line by line.
The second doesn't work because, for the calculation of b, you need to use the old a, not the new a that got generated on the line before (this is actually set to b so you will get b % b, which will generally be zero). The equivalent to the first loop would be:
while b:
oldA = a
a = b
b = oldA % b
print(a)
The tuple assignment in Python can be considered an atomic operation where all the values on the right side are loaded up, then assigned to all the variables on the left side.
def divisor(n):
if n ==1 or n ==2 or n ==3:
return []
else:
result=[]
aux=2
while aux <= n:
if n % aux == 0:
result.append(aux)
aux=aux+1
return result
def func (m,n):
div1=divisor(m)
div2=divisor(n)
result =[]
for x in div1:
for y in div2:
if x == y:
result.append(x)
return result
print(func (x,y))

list comprehension for empty list python 3?

I have an python 3 code as follow:
a = []
b = [[0] * len(a[0]) for _ in range(len(a))]
The above code works fine, but the follow code does not work:
a = []
m, n = len(a), len(a[0])
len(a[0]) apppears in both codes, why the list comprehension does not through IndexError: list index out of range.
Thanks,
range(len(a)) in this case is essentially range(0), which is an empty range:
>>> list(range(0))
[]
Because the collection being iterated over is empty, the comprehension never runs, so a[0] is never evaluated.
It's similar to how this loop prints nothing:
for _ in []:
print("SOME TEXT!")
[] is empty, so the for loop never iterates.
With m, n = len(a), len(a[0]) however, a[0] is run regardless of the length of a, so a[0] is evaluated, and you get an error.

How to remove tuple from zip?

so i have a bunch of numbers i've tupled but am having difficulty remove an item from the zipped list.
so far i've tried .remove on the list but that gave me an error.
is there an easy way of doing this?
this is my current code:
Example data:
QueenRowColumn: 3,3
TheComparisonQueen: 7,3
def CheckQueenPathDown(self, QueenRowColumn, TheComparisonQueen):
row = []
column = []
CurrentLocation = QueenRowColumn
#MoveLocation = TheComparisonQueen
a = QueenRowColumn[0]
b = QueenRowColumn[1]
for i in range (-7,0):
row.append(CurrentLocation[1] - i)
column.append(a)
Down = zip(row,column)
#Down.remove(TheComparisonQueen)
return Down
if i, for example were to remove "TheComparisonQueen" from the list of tuples, how would i do it?
If you just looking to drop TheComparisonQueen from iterator of tuples you can return values that are not equal to TheComparisonQueen using a list comprehension or a generator expression.
# List Comprehension
Down = [(i,j) for i,j in zip(row,column) if (i,j) != TheComparisonQueen]
# Generator Expression
Down = ((i,j) for i,j in zip(row,column) if (i,j) != TheComparisonQueen)

Resources