For this exercise, use the following 2D array, which is already declared and initialized in your programming environment below.
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
Your task is to determine whether each item in the array above is divisible by 3 or not. If an item is divisible by 3, then leave that value as-is in the array, but if it is not divisible by 3, then replace that value in the array with a 0. Remember that you will need to use modular division from Unit 2 to determine if a value is divisible by 3. Finally, print out the array in the format as seen in the sample run below.
Note: Be sure that your program accounts for arrays of any size, not just arrays that are 5 x 5. Your program will be tested against arrays of size n by n. It should work for any square array, not just the one shown. You should also use for loops in your program, not while loops.
Sample Run
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
Answers
Answer:
rows = int(input(''))
columns = int(input(''))
array = []
for a in range(columns):
numbers = input('').split(' ')
array.append(numbers)
for b in array:
for c in range(len(b)):
if int(b[c]) % 3 != 0:
b[c] = '0'
for d in array:
print(' '.join(d))
#Written in Python 3.6.9
Explanation:
Sample Input:
5
5
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
Sample Output:
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
Answer:
# We define array simple_arr as a list whose elements are lists
simple_arr = [[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]]
# Create a function to calculate the average
def mean_arr(arr_arg):
count_arr = 0
sum_arr = 0
# Loop through all array elements with counting the number and sum of elements
for row in arr_arg:
for elem in row:
count_arr += 1
sum_arr += elem
res = sum_arr / count_arr
return res
print(mean_arr(simple_arr))
Explanation:
2/3