-2

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)
  • You say you want to sum the elements of two arrays, but the desired output is not a summation. Can you explain the logic of how you arrive at the desired output, given you input example. – itprorh66 Mar 04 '23 at 18:33
  • Are you even allowed to use lists? If so, what methods are you allowed to use? – Unmitigated Mar 04 '23 at 18:45
  • Why aren't we aloud to use built in funs (except for `len`)? Unless you are solving some specific python exercise, you can use these functions anytime. – sbottingota Mar 05 '23 at 07:22

6 Answers6

2

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]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Neat, but hard to understand. – sbottingota Mar 05 '23 at 06:39
  • 1
    @sbottingota, I don't think so, that's relative to one's skills and knowledge of Python basics – RomanPerekhrest Mar 05 '23 at 06:43
  • Agreed. However, for the benefit of less skilled python programmers, you could explain your code a bit better. (e.g. `array_2[::-1]` reverses array_2, `zip()` 'interlinks' the arrays, etc.) – sbottingota Mar 05 '23 at 06:47
  • @sbottingota, walk through this forum and put attention to a plenty of accepted answers which have just a few word of explanation like "you can use" (like this https://stackoverflow.com/a/45965003/3185459)/ If people with more than 500K score have a right to do that than I want to be able to make similar short. For me - it's not about "benefits for you" or "benefit of less skilled", for me it's about equality and fairness. P.S. I won't explain that basics because you just demanded. – RomanPerekhrest Mar 05 '23 at 07:11
1

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))
Michael M.
  • 10,486
  • 9
  • 18
  • 34
1

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]
sbottingota
  • 533
  • 1
  • 3
  • 18
0

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
An Le
  • 1
  • 2
0

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]

S_IROTH
  • 210
  • 1
  • 5
0

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))]
Alain T.
  • 40,517
  • 4
  • 31
  • 51