-1

I'm trying to code a program that compares elements between two equal lengthed lists, and uses the smallest number for each element and puts it into a new list. This is my code so far:

def func_0(arr_1, arr_2) :
    arr_3 = []
    if len(arr_1) == len(arr_2) :
        for num in arr_1:
            arr_3. append (min(min(arr_1), min(arr_2) ) )
        return arr_3
    else:

        print("Try again")
print(func_0( [1, 2,3], [3, 1,5]))

I think what I need to do is add indexes for the append line, but I'm not sure how to do it. Any help will be appreciated.

4 Answers4

2

You should iterate both lists in parallel and compare each item individually. See this question for an explanation.

Here is a fixed version of your method:

def func_0(arr_1, arr_2) :
    arr_3 = []
    if len(arr_1) == len(arr_2) :
        for num1, num2 in zip(arr_1, arr_2):
            arr_3.append(min(num1, num2))
        return arr_3
    else:
        print("Try again")

That being said, this can be implemented in a one-liner:

def func_0(arr_1, arr_2):
    return [min(tup) for tup in zip(arr_1, arr_2)]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

You can use a list comprehension with zip.

def func_0(arr_1, arr_2) :
    if len(arr_1) == len(arr_2) :
        return [min(a,b) for a, b in zip(arr_1, arr_2)]
    else:
        print("Try again")

map could also be used.

def func_0(arr_1, arr_2) :
    if len(arr_1) == len(arr_2) :
        return list(map(min, zip(arr_1, arr_2)))
    else:
        print("Try again")
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Just compare each element:

def func_0(arr1, arr2):
    result = []
    for n1, n2 in zip(arr1, arr2):
        result.append(min([n1,n2]))
    return result

Note that zip will not break if your lists are of differing length; it will only compare over the min number of elements. This may or may not be desired behavior.

anon01
  • 10,618
  • 8
  • 35
  • 58
0

If you wish to find the smallest value in each list then...


for i, num in enumerate( arr_1 ):
    if num < arr_2[ i ]:
        arr_3.append( num )
    else:
        arr_3.append( arr_2[ i ] )
print( arr_3 )
Derek
  • 1,916
  • 2
  • 5
  • 15