[英]Given a matrix mat of size 3 x 3. Find all the even numbers situated in each of the row(s) whose end cumulative sum is greater than or equal tO 150
PROBLEM: Given a matrix mat of size 3 x 3. Find all the even numbers situated in each of the row(s) whose end cumulative sum is greater than or equal to 150. 问题:给定大小为3 x 3的矩阵垫,请找出位于其最终累积总和大于或等于150的每一行中的所有偶数。
I am able to find sum but not able to extract row wise sum and also I have issues in assigning these row wise even number sum to a variable. 我能够找到和,但无法提取按行和,并且在将这些按行偶数和分配给变量时也遇到问题。
So My code looked but then I don't know how to extract the row wise sum of even numbers. 因此,我的代码看起来不错,但是后来我不知道如何提取偶数的行明智和。
import numpy as np
mat = np.array([[51,21,14],
[56,85,22],
[99,666,230]]).reshape(3,3)
mat2=mat[mat%2==0]
res_mat=np.cumsum(mat2[:1])
print(mat2)
print(res_mat)
this answer won't be any good if using numpy is a requirement for your problem, not using it might be easier though. 如果使用numpy解决您的问题,此答案将不会有什么好处,但是不使用它可能会更容易。
mat = [[51, 21, 14], [56, 85, 22], [99, 666, 230]]
even_numbers_in_target_rows = list()
for row in mat:
if sum(row) >= 150:
for val in row:
if val % 2 == 0:
even_numbers_in_target_rows.append(val)
print(even_numbers_in_target_rows)
Steps: 脚步:
If I understand the problem correctly (and I feel that it is written in an awkward way), you have to find the rows whose sums are >= 150: 如果我正确理解了该问题(并且感觉写起来很尴尬),则必须找到总和> = 150的行:
rows = mat[mat.sum(axis=1) >= 150]
And then choose the even numbers from them: 然后从中选择偶数:
rows[rows % 2 == 0]
#array([ 56, 22, 666, 230])
Note: the question is a bit ambiguous because it is not clear whether "whose" refers to the rows or to the even numbers within. 注意:这个问题有点模棱两可,因为不清楚“谁”是指行还是偶数。 I'm assuming the latter.
我假设是后者。 The former would be easier.
前者会更容易。
You can use np.bincount
together with np.where
您可以将
np.bincount
与np.where
一起使用
# find even numbers
even = mat&1 == 0
# translate mask into coordinates
y, x = np.where(even)
# use y coordinate to group into rows
np.bincount(y, mat[even], mat.shape[0])
# array([ 14., 78., 896.])
You can do this by taking the sum along each row and using the resultant boolean array to index into the original. 您可以通过沿每一行取和,然后使用所得的布尔数组将其索引到原始数组中来进行此操作。 Then, just get the even numbers:
然后,只需获得偶数:
mat = np.array([[51, 21, 14],
[56, 85, 22],
[99, 666, 230]])
uniques = np.unique(mat[mat.sum(axis=1) > 150])
uniques[uniques % 2 == 0]
Output: 输出:
array([ 22, 56, 230, 666])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.