Wiggs Wiggs - 2 months ago 8
Python Question

Pair 2 elements in a list and make a conditional statement to see if the pairs are equal to each other

So I have this homework assignment and seem to be stuck on this question.

write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains three pairs of integers, and False otherwise.

Example:

>>>threePairs([5, 6, 3, 2, 1, 4])
False

>>>threePairs([1, 1, 2, 2, 2, 2])
True


I've tried using indexes and I don't really know how to slice so I'm stuck in figuring out how I make those pairs equal to each other in the condition so it is True.

This is what I had previous to deleting it and trying again.

def threePairs(aList):
if [0] == [1] and [2] == [3] and [4] == [5]:
return True
else:
return False

Answer

You don't need to slice, you need index access (as a side note, you should ask your teacher if they've ever heard of pep8, three_pairs(mylist) would be far better):

def threePairs(aList):
    if aList[0] == aList[1] and aList[2] == aList[3] and aList[4] == aList[5]:
        return True
    else:
        return False

But if you're ever returning True and False like this, you can just return the result of the comparison:

def threePairs(aList):
    return aList[0] == aList[1] and aList[2] == aList[3] and aList[4] == aList[5]

Though as other answers allude - your examples are not well defined. What if you have:

>>> threePairs([1, 2, 3, 1, 2, 3])

Should that return True, or False?

Comments