How can I solve this problem without any built-in function except len()?

Question:

Given two arrays.

array_1 = [1, 4, 5, 8, None, None, None]
array_2 = [7, 4, 8, 9, 5, None, None]

output:

array_3 = [1, 4, 10, 17, 8, 4, 7]

It will start from the first element of the first array and the last element of the second array and return the sum of them.

For example, (1+None)= 1, (4+None)=4, (5+5)= 10, (8+9)=17 and so on.

My attempt at this problem,

array_1= [1,4,5,8,None,None,None]
array_2= [7,4,8,9,5,None,None]

for i in range (len(array_1)):
  for j in range (len(array_2)-1,0,-1):
    if i == None:
      array_1[i]=0
    elif j==None:
      array_2[j]= 0
    L= array_1[i]+array_2[j]
    print(L)
Asked By: Zabia Hossain

||

Answers:

Use list comprehension with check for None values:

res = [(x or 0) + (y or 0) for x, y in zip(array_1, array_2[::-1])]

[1, 4, 10, 17, 8, 4, 7]
Answered By: RomanPerekhrest

You can reverse the second list, then zip() them together, change Nones to 0s, then sum. If you don’t fancy list comprehensions, you can do it like this:

def backsum(lst_1, lst_2):
    out = []
    for a, b in zip(lst_1, reversed(lst_2)):
        if a is None:
            a = 0
        elif b is None:
            b = 0
        out.append(a + b)
    return out


lst_1 = [1, 4, 5, 8, None, None, None]
lst_2 = [7, 4, 8, 9, 5, None, None]
print(backsum(lst_1, lst_2))
Answered By: Michael M.

You would not want to do a nested for loop for this problem as for every index of the first array, you will iterated over all indexes of the second array. Instead you want to use one for loop that represents both the first element of the first array and the last element of the second array (you can think of reversing the second array and iterating the same indexes). Instead try:

array1 = [1,2,3]
array2 = [10,20,30]

for idx in range(len(array1)):
    print( array1[idx]+array2[len(array2)-1-idx] )

Note the "length of array 2 minus 1", as the last index is one less than the length. This also assumes that both arrays are the same length.

Your i and j variables are integers as you are using them to iterate through the indexes of an array. You need to check if the index of the array that they are iterating through is None.

if array_k[i] == None
Answered By: An Le

You could do:

array_1 = [1, 4, 5, 8, None, None, None]
array_2 = [7, 4, 8, 9, 5, None, None]

# replace None with 0
array_1 = [0 if i is None else i for i in array_1]
array_2 = [0 if i is None else i for i in array_2]

# reverse array_2
array_2.reverse()

output_array = [array_1[i] + array_2[i] for i in range(len(array_1))]

print(output_array)

output:

[1, 4, 10, 17, 8, 4, 7]

Alternatively, you could use numpy like:

import numpy as np

array_1 = np.array([1, 4, 5, 8, None, None, None])
array_2 = np.array([7, 4, 8, 9, 5, None, None])

array_1[array_1 == None] = 0
array_2[array_2 == None] = 0

array_2 = np.flip(array_2)

output_array = array_1 + array_2

print(output_array)

output:

[1, 4, 10, 17, 8, 4, 7]
Answered By: sbottingota

Something like this


array_1 = [1, 4, 5, 8, None, None, None]
array_2 = [7, 4, 8, 9, 5, None, None]


def combine(A,B):
    r=len(A)-1
    C = [0] * len(A)
    for x in range( len(A) ):
        C[x] = 0
        if A[x] != None:
            C[x] = A[x]

        if B[r-x] != None:
            C[x] = C[x] + B[r-x]
    return C

print('array_1 ', array_1)
print('array_2 ', array_2)
print('------')

array_3=combine(array_1, array_2)


print('array_3 ', array_3)

Output:


array_1  [1, 4, 5, 8, None, None, None]
array_2  [7, 4, 8, 9, 5, None, None]
------
array_3  [1, 4, 10, 17, 8, 4, 0]

Answered By: S_IROTH

Assuming the two lists are always the same length, you can go through the second list backwards and use the size of the resulting list as index to add the value of the first list (use or 0 to process None values as numbers). This will avoid the need to manage indexes or ranges.

array_1 = [1, 4, 5, 8, None, None, None]
array_2 = [7, 4, 8, 9, 5, None, None]

result = []
for v2 in array_2[::-1]:
    result     += [array_1[len(result)] or 0]
    result[-1] += v2 or 0

print(result)
[1, 4, 10, 17, 8, 4, 7]

This only uses the len() built-in function (not even range or enumerate). But you could do it without using any build-in functions by writing your own recursive function:

def addReverse(A,B):
    if not A or not B:
        return []
    return [(A[0] or 0)+(B[-1] or 0)] + addReverse(A[1:],B[:-1])

print(addReverse(array_1,array_2))
[1, 4, 10, 17, 8, 4, 7]

If you are also allowed to use the range object (technically a built-in class, not a function), the result can be computed using a list comprehension:

result = [(array_1[i] or 0)+(array_2[-i-1] or 0) for i in range(len(array_1))]
Answered By: Alain T.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.