I’ve tried posting this question onto other websites and I have received, lightly to say, little to no feedback that helps. This is the question at hand: Image Here
The code is asking to divide the numbers in a 2d array by 3, and if they’re not divisible by 3, then return them to a 0 in the array. This is the current code I have:
a = [[34,38,50,44,39], [42,36,40,43,44], [24,31,46,40,45], [43,47,35,31,26], [37,28,20,36,50]] #print it def PrintIt(x): for r in range(len(x)): for c in range(len(x[0])): print(x[r][c], end = " ") print("") #is supposed to divide and return the sum. but does not def divSUM(x): sum = 3 for r in range(len(x)): for c in range(len(x[0])): sum = x[r][c] % 3 if sum != 0: return 0 return sum divSUM(a)
The divide (divSUM) returns as nothing. and I’m unsure if numpy would work, every time I try it says its outdated so I assume it doesn’t. Any help would be nice, but I’m mainly having issues with putting the undivisble by 3 numbers to a 0.
Advertisement
Answer
(What I understood is that if the number % 3 == 0 you let the same number otherwise you put 0.)
I propose to work with numpy
it’s easy to do it in a simple line :
import numpy as np a = np.array([[34,38,50,44,39], [42,36,40,43,44], [24,31,46,40,45], [43,47,35,31,26], [37,28,20,36,50]]) result = np.where(a%3 ==0, a, 0) >>>result array([[ 0, 0, 0, 0, 39], [42, 36, 0, 0, 0], [24, 0, 0, 0, 45], [ 0, 0, 0, 0, 0], [ 0, 0, 0, 36, 0]])
Otherwise, the problem with your code is that you wrongly choose the place where to put return
.
So, you have to do this:
def divSUM(x): result = [] for r in x: tmp = [] for c in r: if c % 3 != 0: tmp.append(0) else: tmp.append(c) result.append(tmp) return result