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

Changing the previous and next value of a number that is being doubled in python

I’m a student new to programing and wanted help with an assignment that asks us to double all the numbers in an array but if the previous and the number that comes after the number that is currently being doubled are equal, then change the number that comes after the number that is being doubled.
This is what I currently have:

from array import *
vals = array('i', [0, 2, 5, 4, 1, 0, 3, 3, 6, 7])
print(vals)
 
for i in range(len(vals)):
    if i >= 0:
        if vals[i-1] == vals[i+1 < i]:
         vals[i] = vals[i] *2
         print(vals[i])

So far I’ve written the code is working properly, the output required is [0, 4, 10, 0, 2, 0, 6, 6, 0, 14], we are basically required to double the values in the array and in the procec to replace for example:
if the value that is being doubled currently is 3, if the value that came before it and the one that comes after it are equal then replace the value that comes after with 0, in this case [6, 3, 6] replace the 2nd 6 with 0

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 :

This produces the desired output. I used a list instead of an array.

vals = [0, 2, 5, 4, 1, 0, 3, 3, 6, 7]

vals[0] *= 2
for i in range(1, len(vals)-1):
    if vals[i - 1] == vals[i + 1]:
        vals[i + 1] = 0
    vals[i] *= 2
vals[-1] *= 2

print(vals)

Output:

[0, 4, 10, 0, 2, 0, 6, 6, 0, 14]
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