In place of 1 , x values should be filled according to the index.
My code is :
x = [0.5697071 0.47144773 0.45310486]
z_prime= [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1]]
flatten_matrix = [val for val in z_prime ]
for val in flatten_matrix:
for j in val:
if(j!=0):
z= x
else:
z = 0
print(z)
This gives the output as:
0
0
0
0
0
[0.5697071 0.47144773 0.45310486]
0
[0.5697071 0.47144773 0.45310486]
0
0
[0.5697071 0.47144773 0.45310486]
[0.5697071 0.47144773 0.45310486]
Expected Output:
[ [0, 0, 0], [0, 0, 0.45310486 ], [0, 0.47144773 , 0], [0, 0.47144773, 0.45310486],
Try this:
flatten_matrix = [[x[idx] if elm[idx] == 1 else 0 for idx in range(len(elm))] for elm in z_prime]
As a sidenote: I'd recommend breaking this up into a standalone function, because if you ever come back to this list comprehension it'll be incomprehensible.
Consider something like this (which may be sligthly less performant, but much more readable)
def flatten_matrix(x, z_prime):
if len(x) != len(z_prime[0]):
raise ValueError("x and z_prime must have the same number of columns")
#Maybe even add a check here that all the elements of z_prime are 0 or 1
#Or add a check that all elements in z_prime have the same length?
output = [[0] * len(x) for i in range(len(z_prime))] #Creates the output list with correct format
for row_idx, elm in enumerate(z_prime): #Iterates through the rows of z_prime
for col_idx, num in enumerate(elm): #Iterates through the columns of z_prime
if num == 1:
output[row_idx][col_idx] = x[col_idx]
else:
output[row_idx][col_idx] = 0
return output
Related
I am struggling with what is hopefully a simple problem. Haven't been able to find a clear cut answer online.
The program given, asks for a user input (n) and then produces an n-sized square matrix. The matrix will only be made of 0s and 1s. I am attempting to count the arrays (I have called this x) that contain a number, or those that do not only contain only 0s.
Example output:
n = 3
[0, 0, 0] [1, 0, 0] [0, 1, 0]
In this case, x should = 2.
n = 4
[0, 0, 0, 0] [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 0, 0]
In this case, x should also be 2.
def xArrayCount(MX):
x = 0
count = 0
for i in MX:
if i in MX[0 + count] == 0:
x += 0
count += 1
else:
x += 1
count += 1
return(x)
Trying to count the number of 0s/1s in each index of the matrix but I am going wrong somewhere, could someone explain how this should work?
(Use of extra python modules is disallowed)
Thank you
You need to count all the lists that contain at least once the number one. To do that you can't use any other module.
def count_none_zero_items(matrix):
count = 0
for row in matrix:
if 1 in row:
count += 1
return count
x = [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]
count_none_zero_items(x)
Also notice that i changed the function name to lower case as this is the convention in python. Read more about it here:
Python3 Conventions
Also it's worth mentioning that in python we call the variable list instead of array.
Those look like tuples, not arrays. I tried this myself and if I change the tuples into nested arrays (adding outer brackets and commas between the single arrays), this function works:
def xArrayCount(MX):
x = 0
count = 0
for i in matrix:
if MX[count][count] == 0:
count += 1
else:
x += 1
count += 1
return x
I have a problem. It is a 2D list of non-negative integers will be given like
0, 0, 2, 0, 1
0, 2, 1, 1, 0
3, 0, 2, 1, 0
0, 0, 0, 0, 0
I have to drop the numbers, number columns. e.g. drop down the 1's down 1 column, the 2's down 2 columns, the 3's down 3 columns, and so on. If the number can't be moved down enough, wrap it around the top. (e. g If there is a 3 in the second-to-last row, it should wrap around to the first row.) If two numbers map to the same slot, the biggest number takes that slot.
After this transformation the given matrix above will end up like:
0, 0, 2, 0, 0
3, 0, 0, 0, 1
0, 0, 2, 1, 0
0, 2, 0, 1, 0
Here's my trivial solution to the problem (Assumes a list l is pre-set):
new = [[0] * len(l[0]) for _ in range(len(l))]
idx = sorted([((n + x) % len(l), m, x) for n, y in enumerate(l) for m, x in enumerate(y)], key=lambda e: e[2])
for x, y, z in idx:
new[x][y] = z
print(new)
The strategy is:
Build a list new with 0s of the shape of l
Save the new indices of each number in l and each number as tuple pairs in idx
Sort idx by each number
Assign indices from idx to the respective numbers to new list
Print new
I am not satisfied with this strategy. Is there a neater/better way to do this? I can use numpy.
Let's say you have
a = np.array([
[0,0,2,0,1],
[0,2,1,1,0],
[3,0,2,1,0],
[0,0,0,0,0]])
You can get the locations of the elements with np.where or np.nonzero:
r, c = np.nonzero(a)
And the elements themselves with the index:
v = a[r, c]
Incrementing the row is simple now:
new_r = (r + v) % a.shape[0]
To settle collisions, sort the arrays so that large values come last:
i = v.argsort()
Now you can assign to a fresh matrix of zeros directly:
result = np.zeros_like(a)
result[new_r[i], c[i]] = v[i]
The result is
[[0 0 2 0 0]
[3 0 0 0 1]
[0 0 2 1 0]
[0 2 0 1 0]]
I suggest doing it like this if only because it's more readable :-
L = [[0, 0, 2, 0, 1],
[0, 2, 1, 1, 0],
[3, 0, 2, 1, 0],
[0, 0, 0, 0, 0]]
R = len(L)
NL = [[0]*len(L[0]) for _ in range(R)]
for i, r in enumerate(L):
for j, c in enumerate(r):
_r = (c + i) % R
if c > NL[_r][j]:
NL[_r][j] = c
print(NL)
We have a list
list = [1, 1, 1, 0, 1, 0, 0, 1]
I am trying find a function that would count the number of 0's before each item and then multiply this number by 3.
def formula(n):
for x in list:
if x == 1:
form = n * 3
return form
#If x is 1, count the number of zeros right before x and multiply this by 3,
For example for the list above, the first element is a 1 and there are no numbers right before it, the program should compute 0 * 3 = 0, for the second item, which is also a 1, the number right before it is also not a zero, the program should also compute 0 * 3 = 0. The 4th element is 0 so the program should ignore, For the 5th element which is a 1, the number right before it is a 0, the programme to compute 1 * 3 = 3, for the 6th element the number right before it is a 1, the system should compute 0 * 3 = 0. The 7th element is a 0, since x is not equal to 1 the program should not do anything. For the last element which is a 1, the last two numbers before it are zeros, the program should compute 2 * 3 = 6
I believe you are looking for a generator, with a simple counter:
def get_values (list):
n = 0
for x in list:
if x == 1:
yield n * 3
n = 0 # reset the counter
elif x == 0:
n += 1 # increment the counter
print(list(get_values([1, 1, 1, 0, 1, 0, 0, 1])))
# [0, 0, 0, 3, 6]
Try this,
def formula(l):
count_zero = 0
result = []
for i in l:
if i == 1:
result.append(3*count_zero)
count_zero = 0
elif i == 0:
count_zero += 1
return result
# Test case
l = [1, 1, 1, 0, 1, 0, 0, 1]
result = formula(l)
print(result)
# [0, 0, 0, 3, 6]
Here is my solution for the problem.
test_list = [1, 1, 1, 0, 1, 0, 0, 1]
def formula(list):
track = []
start = 0
for i,n in enumerate(list):
count_list_chunk = list[start:i]
if count_list_chunk.count(0) > 0 and n != 0:
start = i
if n != 0:
track.append( count_list_chunk.count(0)*3 )
return track
print formula(test_list)
#[ 0, 0, 0, 3, 6]
I have a matrix [[0 0 0 0 0 0 0][1 0 0 1 0 0 1][2 1 0 0 1 0 0]].I need to return the index of element which is largest in the last row but less than 2 also,the it should return the index which is of highest value.
For example,in my matrix,I need the program to return me M[2,4],2,4 as the solution.My program is running,but it is returning the value at M[2,1] position.
M=[[0 0 0 0 0 0 0]
[1 0 0 1 0 0 1]
[2 1 0 0 1 0 0]]
ma=0
for i in range(1,2):
for j in range(0,7):
if M[i,j]<2 and ma<=M[i,j]:
ma=M[i,j]
return M[i,j],i,j
The problem is it returns too early. You should make it return after all the elements has been scanned. In this case the return statement should not be placed inside the inner loop, put it outside the outer for loop. Also I think you need to keep track of the highest value's index along with ma since i, j would be the value of the last element after the loop finished.
The original code's syntax seems incorrect so I have made some modifications:
def test():
M=[[0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 1],
[2, 1, 0, 0, 1, 0, 0]]
ma=0
maxi = maxj = 0
for i in range(0,3):
for j in range(0,7):
if M[i][j] < 2 and ma <= M[i][j]:
ma = M[i][j]
maxi = i
maxj = j
return(ma, maxi, maxj)
print(test())
This code outputs the desired result: (1, 2, 4)
I'm starting to learn Python, I just started with a simple example. The question was to count mines near each place in a table. Consider input file below:
4 4
*...
....
.*..
....
3 5
**...
.....
.*...
0 0
The output should be like
Field #1:
*100
2210
1*10
1110
Field #2:
**100
33200
1*100
And my code is:
#!/usr/bin/python
import pprint
fin = open("1.2.in")
fout = open("1.2.out")
while True:
i, j = [int(x) for x in fin.readline().split()]
if(i == 0):
break
arr = []
for k in range(0,i):
line = fin.readline();
arr.append(list(line))
pprint.pprint(arr)
resarr = [[0]*j]*i
for row in range(0,i):
for col in range(0,j):
for rowIndex in range(-1,2):
for colIndex in range(-1,2):
# print row,rowIndex, col,colIndex
if (row + rowIndex < i) and (row + rowIndex >= 0) and ( col + colIndex < j) and (col+colIndex >=0) and (rowIndex != 0 or colIndex != 0):
#pprint.pprint(resarr[row][col])
#if arr[row+rowIndex][col+colIndex] == "*":
#print row,rowIndex, col,colIndex, " ", arr[row+rowIndex][col+colIndex]
#print resarr[row][col]
resarr[row][col] += 1
#pprint.pprint(resarr)
# print col+colIndex
print i,j
pprint.pprint(resarr)
I don't know what's wrong, but when I want to increment resarr, a total column is incremented.
Your problem is
resarr = [[0]*j]*i
This means: Take i references to the same list defined by [0]*j and create a list of those.
The thing you want is:
resarr = [[0]*j for _ in range(i)]
This creates a new list ([0, 0, ...]) i times instead.
See this:
>>> a = [0] * 4
>>> a
[0, 0, 0, 0]
>>> b = [a] * 4
>>> b
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> id(b[0]) # get the "address" of b[0]
42848200
>>> id(b[1]) # b[1] is the same object!
42848200
>>> b[0][0] = 1
>>> b
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]