Home > OS >  Changing the previous and next value of a number that is being doubled
Changing the previous and next value of a number that is being doubled

Time:03-12

I want 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.

CodePudding user response:

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]
  • Related