Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conversion – beginner

I have a hard time doing the arithmetic statement

Convert the tuple, "Third" to an array.

Double all the elements in "Third"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]

>Solution :

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 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(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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading