﻿ NumPy - Dot product of two arrays of different dimensions

# Advanced NumPy Exercises - Dot product of two arrays of different dimensions

## NumPy: Advanced Exercise-1 with Solution

Write a NumPy program to find the dot product of two arrays of different dimensions.

Sample Solution:

Python Code:

``````import numpy as np
# Define the two arrays
nums1 = np.array([[1, 2], [3, 4], [5, 6]])
nums2 = np.array([7, 8])
print("Original arrays:")
print(nums1)
print(nums2)
# Find the dot product
result = np.dot(nums1, nums2)
# Print the result
print("Dot product of the said two arrays:")
print(result)
``````

Sample Output:

```Original arrays:
[[1 2]
[3 4]
[5 6]]
[7 8]
Dot product of the said two arrays:
[23 53 83]
```

Explanation:

In the above exercise -

nums1 = np.array([[1, 2], [3, 4], [5, 6]]): This code creates a 2D NumPy array with shape (3, 2) containing the values [[1, 2], [3, 4], [5, 6]] and assigns it to the variable nums1.

nums2 = np.array([7, 8]): This code creates a 1D NumPy array with shape (2,) containing the values [7, 8] and assigns it to the variable nums2.

result = np.dot(nums1, nums2): Here dot() function performs dot product between nums1 and nums2, and assigns the result to the variable result. Since nums1 has shape (3, 2) and nums2 has shape (2,), the dot product results in a 1D array with shape (3,) containing the values [23, 53, 83].

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value:

Example:

```def tips_map_values(obj, fn):
ret = {}
for key in obj.keys():
ret[key] = fn(obj[key])
return ret
users = {
'Owen': { 'user': 'Owen', 'age': 29 },
'Eddie': { 'user': 'Eddie', 'age': 15 }
}

print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}
```

Output:

```{'Owen': 29, 'Eddie': 15}
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook