w3resource

Calculating average with NumPy memory view in Python

Python Memory Views Data Type: Exercise-4 with Solution

Write a Python program that creates a memory view from a NumPy array and calculates the average of its elements.

Sample Solution:

Code:

import numpy as np

# Create a NumPy array
nums = np.array([2, 4, 6, 8, 10], dtype=np.int32)

# Create a memory view from the NumPy array
memory_view = memoryview(nums)

# Calculate the average using the memory view
total = 0
for element in memory_view:
    total += element
average = total / len(memory_view)
print("NumPy Array:", nums)
print("Memory View:", memory_view)
print("Average:", average)

Output:

NumPy Array: [ 2  4  6  8 10]
Memory View: <memory at 0x00000266DBB4E348>
Average: 6.0

In this exercise above, we first import the "numpy" library and create a NumPy array called 'nums' with some integer values. Then, we create a memory view called 'memory_view' from the 'nums' array. We calculate the average by iterating through the memory view elements and summing them up. Finally, divide the total by the memory view length to get the average.

Flowchart:

Flowchart: Calculating average with NumPy memory view in Python.

Previous: Creating NumPy memory views: 1D and 3D array examples in Python.
Next: Modifying binary files using Python memory views.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-memory-views-exercise-4.php