Ted Idzikowski Ted Idzikowski - 2 months ago 9
Python Question

Erasing pairs of equal ranking in the same list?

I've got a function called erasing_pairs that should take a string as input and return a copy of list l where all the pairs from l are removed and elements of the new list shuffled. The docstrings below explain in more details.

The desired outcome is like below:

>>> erase_pairs(['9♠', '5♠', 'K♢', 'A♣', 'K♣', 'K♡', '2♠', 'Q♠', 'K♠', 'Q♢', 'J♠', 'A♡', '4♣', '5♣', '7♡', 'A♠', '10♣', 'Q♡', '8♡', '9♢', '10♢', 'J♡', '10♡', 'J♣', '3♡'])
['10♣', '2♠', '3♡', '4♣', '7♡', '8♡', 'A♣', 'J♣', 'Q♢']

Here's how the function is expected to look like:

def erase_pairs(l):

return without_pairs

So basically, I explained the desired outcome. Here's an attempt I made, but to no avail:

def erase_pairs(l):
without_pairs = [x for x in l if l.count((l[x][0])) == 1]
return without_pairs


I'm going to make one small change to your data, for the sake of convenience. Instead of 10♠, use T♠, This means you can compare the values by looking at the first character.

Return single item lists. Avoid possible index errors later.

if len(l) < 2:
    return l

Sort first. This brings all potential pairs next to each other, for quick removal:

l.append([None]) # This helps check at the end of the list, 
                 # while avoiding accidentally reading beyond the end          
                 # of the list.

Then go through the list in pairs, adding any unpaired items to no_pairs.

no_pairs = []
i = 1
while i < len(l):
    if l[i-1][0] != l[i][0]:
        i += 1
        i += 2    

shuffle and return

return no_pairs