Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeSignal - 'Mutate Array'

Tags:

python

The coding question asks:

Given an integer n and an array a of length n, your task is to apply the following mutation to a:

Array a mutates into a new array b of length n. For each i from 0 to n - 1, b[i] = a[i - 1] + a[i] + a[i + 1]. If some element in the sum a[i - 1] + a[i] + a[i + 1] does not exist, it should be set to 0. For example, b[0] should be equal to 0 + a[0] + a1.

My Code:

def solution(n, a):
    b = [None] * n
    for i in range(0, n-1):
        print('i = ', i)
        if i <= 0:
            b[i] = 0 + a[i] + a[i+1]
            print('IF 1')
        elif i >= n-1:
            b[i] = a[i-1] + a[i] + 0
            print('IF 2')
        else:
            b[i] = a[i-1] + a[i] + a[i+1]
            print('IF 3')
    return b

The issue is that the for loop does not seem to run a sufficient amount of times, and I cannot change the range according to the question. Any ideas? See results below.

enter image description here

like image 741
Conor Avatar asked Aug 27 '26 05:08

Conor


1 Answers

The other solution failed for single element array. This should work fine.

def solution(a):
    b = []
    #print(b)
    for i in range(len(a)):
        if len(a) == 1:
            b.append(a[0])
        else:

            if i == 0:
                # b[i] = 0 + a[i] + a[i+1]
                b.append(0 + a[i] + a[i+1])
                print(b[i])
            elif i >= len(a) - 1:
                b.append(a[i - 1] + a[i] + 0)
            else:
                # b[i] =  a[i - 1] + a[i] + a[i + 1]
                b.append(a[i - 1] + a[i] + a[i + 1])
    return b
like image 178
Abhishek Porwal Avatar answered Aug 28 '26 18:08

Abhishek Porwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!