user7253631
user7253631

Reputation:

Python If last N values of list is same as last N values of list 2

I am doing practice past paper questions to revise for my exam next week

Let's say i have two lists

a=[1,2,3,4]
b=[1,2,3,4]

and a variable n set to a value i.e. 2 I need to create a function that checks if the last "n" values are the same in list1 and list2 in the same order.

One variant using a for loop and one without a loop

In this case it would return true, since 3,4 are the same in list 1 and 2

If b=[1,2,4,3] it would return false

My current code without a loop is:

def compare1(a,b,n):
    if a[-n:]==b[-n:]:
        return True
    else:
        return False

I believe this works when i test it

But how would i convert this to have a for loop aswell? If i add:

def compare2(a,b,n):
    for i in a and b:
        if a[-n:]==b[-n:]:
            return True
        else:
            return False

this would work but the for loop isn't doing anything

Upvotes: 1

Views: 497

Answers (2)

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

Reputation: 7091

Without loop

def compare1(a,b,n):
    return a[-n:] == b[-n:]

With loop You need to iterate from last to nth from last

def compare2(a,b,c):
    for i in xrange(1,c + 1):
        if a[-i] != b[-i]:
            return False
    return True

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55469

There are a few ways to do this. You could loop over the indices of the lists, or you could zip the lists together and loop directly over the items. Here are a few examples. I've also optimised your compare1 function.

def compare1(a, b, n):
    return a[-n:] == b[-n:]

def compare2(a, b, n):
    for i in range(-n, 0, 1):
        if a[i] != b[i]:
            return False
    return True

def compare3(a, b, n):
    for u, v in zip(a[-n:], b[-n:]):
        if u != v:
            return False
    return True

def compare4(a, b, n):
    return all(u == v for u, v in zip(a[-n:], b[-n:]))

# test

funcs = (compare1, compare2, compare3, compare4)

a = [1, 2, 3, 4]
b = [5, 6, 3, 4]
c = [1, 2, 5, 6]

for compare in funcs:
    print(compare.__name__)
    print(a, b, compare(a, b, 2))
    print(a, c, compare(a, c, 2))
    print()

output

compare1
[1, 2, 3, 4] [5, 6, 3, 4] True
[1, 2, 3, 4] [1, 2, 5, 6] False

compare2
[1, 2, 3, 4] [5, 6, 3, 4] True
[1, 2, 3, 4] [1, 2, 5, 6] False

compare3
[1, 2, 3, 4] [5, 6, 3, 4] True
[1, 2, 3, 4] [1, 2, 5, 6] False

compare4
[1, 2, 3, 4] [5, 6, 3, 4] True
[1, 2, 3, 4] [1, 2, 5, 6] False

FWIW, compare1 is the best way to do this, since it does all the looping & testing at the C level rather than using explicit Python code.

Upvotes: 1

Related Questions