🎉 Before you dive into this article...
🚀 Check out our vibrant new community at CoderLegion.com!
💡 Share your knowledge, connect with like-minded developers, and grow together.
👉 Click here to join now!
An array may be a collection of things keep in contiguous memory locations. the idea is to store multiple items of constant kind together. This makes it easier to calculate the position of every part by merely adding Associate in Nursing offset to a base worth eg. memory location of the primary element of the array (usually indicated by the name of the array).
For simplicity, we can think of an array as a fleet of stairs where a value is placed on each step (say one of your friends). Here you can identify the location of any of your friends just by knowing the number of steps they are on. The array can be managed in Python by a module called array.They can be useful when we need to manipulate only values of a specific data type. A user can treat lists like tables.
However, the user cannot constrain the type of items stored in a list.
In this Python programming post I will teach you how to obtain the sum of all the elements of an array, as well as obtain the average of it.
Explanation of the algorithm
Once the matrix is defined, all we have to do is use for into go through the arrays or rows that the matrix has (since a matrix is an array of arrays, or list of lists).
In each route of the row, we simply go through each element of it, where we will already have the true value. It is right here when we are increasing the counter of elements and we are adding to the sum.
Finally we obtain the average, which would be to divide the sum of all the elements by the number of them.
Python source code
Now that I have explained how it works, let's look at the code for the exercise:
"" "
"" "
matrix = [
[7.8, 2.5, 10],
[20, 15.2, 12],
[89, 9, 6.77],
]
All we do is add all the values and divide them by the total elements
Note: if the matrix is a "square" matrix then you could just use
len (matrix) * len (matrix [0])
elements = 0
sum = 0
for row in matrix:
for element in row:
sum + = element
elements + = 1
average = sum / elements
print (
f is "The sum is {summation} and the average is {average}, for the matrix that has {elements} elements"
)
We go through the entire matrix in line 15 , then we go through each element of the row in line 16 and this is where we increase the summation and the element count.
Hope it helps.
Top comments (0)