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

How to Add 5 to each element of an array and replace the old elements with the new ones (after +5)?

See I wrote the code already, and this works for an array with heterogeneous elements (e.g. [2 3 4 5] (different elements), however, if the elements are homogenous (e.g. [2 5 5 8]), the output doesn’t work as expected. How do I fix this?

code below:

import numpy as np

x = np.array([1, 2, 3, 3, 5])

print("arrray x is"+" "+str(x))

print()

i = 0

while i<(len(x)):

    z = (x[i]+5)

    print("The new value for x["+str(i)+"] is"+" "+str(z))

    j = 0

    while j<(len(x)):

        if (x[j]+5) == z:

            x = np.where(x==x[j], z, x)

        j += 1

    i+=1

print()

print("Now the array x is"+" "+str(x))

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

>Solution :

Try this one.

import numpy as np
x = np.array([1, 2, 3, 3, 5])

new_lst = x+5
print(new_lst)

OUTPUT [6, 7, 8, 8, 10]

Thanks, @matszwecja.

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