Issue
Hey guys I am a newbie at Numpy and am trying to learn but having issues. Lets say I have a list and I want to find the total and the product. I can do so in vanilla python:
numbers_list = [5,4,3,2,1]
total = sum(numbers_list)
product = 1
for x in numbers:
product = product * x
The total should be 15 and the product 120. But how can I do it using Numpy?
Solution
Convert the Python list into a Numpy array using numpy.asarray and then use numpy.sum and numpy.prod for calculating the total sum and product respectively, observe:
import numpy as np
numbers_list = [5,4,3,2,1]
numbers_np_array = np.asarray(numbers_list)
total = numbers_np_array.sum()
product = numbers_np_array.prod()
print("The total is: %d" % total)
print("The product is: %d" % product)
Output:
The total is: 15
The product is: 120
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.