I have a hard time doing the arithmetic statement
Convert the tuple, "Third" to an array.
Double all the elements in "Third"
Add the elements in this array to the elements in "Fourth".
To do this, use only 1 arithmetic statement. Store this result as "Fifth" and print it.
Hint Answer should look like this:
Fifth = 2*(_) _____ print (Fifth)
third = (-6,-18,-10,-4,-90,-55,-56)
fourth =[6],[18],[10],[4],[90],[55],[56]
fourth = np.array(fourth)
print(third)
print(type(third))
print("After converting Python tuple to array")
arr = np.asarray(third)
print(arr)
print(type(arr))
fifth = 2*arr
print(fifth)
output:
(-6, -18, -10, -4, -90, -55, -56)
<class 'tuple'>
After converting Python tuple to array
[ -6 -18 -10 -4 -90 -55 -56]
<class 'numpy.ndarray'>
[ -12 -36 -20 -8 -180 -110 -112]
CodePudding user response:
The numpy.ndarray
type (docs) supports addition using the
operator. However, in your example my guess is that 2*arr fourth
will not produce the result you are looking for because fourth
is of shape (7,1)
while arr
is of shape (7,)
, so arr fourth
would be of shape (7,7)
.
There are multiple ways to get fourth
into shape (7,)
. fourth.flatten()
will work (docs), as will numpy indexing, e.g. fourth[:,0]
.
Try this runnable (and editable!) example
import numpy as np
third = (-6,-18,-10,-4,-90,-55,-56)
fourth =[6],[18],[10],[4],[90],[55],[56]
fourth = np.array(fourth)
print(third)
print(type(third))
print("After converting Python tuple to array")
arr = np.asarray(third)
print(arr)
print(type(arr))
print(f"{arr.shape=}, {fourth.shape=}, {fourth.flatten().shape=}, {fourth[:,0].shape=}")
fifth = 2*arr fourth[:,0]
print(f"{fifth=}")
fifth
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>
p.s. when asking a question make sure to post your attempt as well as the traceback of the error produced