John Smith
John Smith

Reputation: 3

Compare items from two lists in Python

The task is to check whether the last 3 digits from corresponding items from two lists are the same. If the items have a length of less than 3, it checks whether they are the same number.

If the two lists have different lengths it should return false, and if both lists have a length of 0, it should return true.

def corresponding_elements_have_same_end(list1, list2):

if len(list1) == len(list2):

    for i in range(0, len(list1)):

        num1 = str(list1[i])
        num2 = str(list2[i])

        if len(num1) <= 3 and len(num2) <= 3:
            return num1 == num2

        else:
            return num1[-3:] == num2[-3:]

else:
    return False

If I run it through this:

print("1.", corresponding_elements_have_same_end([3452, 43600, 10], [3111452, 600, 10]))
print("2.", corresponding_elements_have_same_end([452, 43600], [52, 600]))
print("3.", corresponding_elements_have_same_end([32, 43032], [32, 32]))
print("4.", corresponding_elements_have_same_end([32, 43132, 300], [32, 56132, 3300]))

It prints out

  1. True
  2. False
  3. True
  4. True

When it should print:

  1. True
  2. False
  3. False
  4. True

Upvotes: 0

Views: 660

Answers (3)

bian
bian

Reputation: 1456

def t(m,n):
    if False in map(lambda x,y:str(x)[-3:]==str(y)[-3:],m,n):
        return False
    return True

Upvotes: 1

ml-moron
ml-moron

Reputation: 886

Maybe this is the control flow you are looking for:

def corresponding_elements_have_same_end(list1, list2):
    if len(list1) == len(list2):
        for i in range(len(list1)):
            num1, num2 = str(list1[i]), str(list2[i])
            if len(num1) <= 3 and len(num2) <= 3 and num1 != num2:
                return False
            if num1[-3:] != num2[-3:]:
                return False
        return True
    else:
        return False

Upvotes: 0

niemmi
niemmi

Reputation: 17263

The problem is that the function always checks only one item from the lists and returns immediately no matter the length. When [32, 43032], [32, 32] are compared against each other it checks that 32 == 32 and immediately returns True. If you change the order of first list to [42032, 32] you'd get False instead.

In order to fix the problem the loop needs to be modified so that it returns only in case that numbers don't match. If they do then the next pair of numbers should be checked. If the loop completes then you know that all numbers match. Here's an example:

for i in range(0, len(list1)):
    if str(list1[i])[-3:] != str(list2[i])[-3:]:
        return False

return True

Note that you could implement the loop with zip to make indexing unnecessary:

for x, y in zip(list1, list2):
    if str(x)[-3:] != str(y)[-3:]:
        return False

Upvotes: 2

Related Questions