HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Removing all duplicated pairs in a Python list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
removingallduplicatedpythonlistpairs

Problem

I need a function to remove duplicated pairs from a list. The following is example list:

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

I need remove all pairs [a[i], a[i+1]] if a[i] == a[i+1] until all such pairs eliminated:

[1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]

[1, 2, 3, 5, 5, 2, 2, 3, 1]

[1, 2, 3, 3, 1]

[1, 2, 1] - final list

I wrote a removepairs function:

def removepairs(list):
    result_prev = list
    while True:
        result = __removepairs_once__(result_prev)
        if len(result) == len(result_prev):
            return result
        else:
            result_prev = result

def __removepairs_once__(list):
    result = []
    most_recent_element = None
    for i in list:
        if i != most_recent_element:
            if most_recent_element:
                result.append(most_recent_element)
            most_recent_element = i
        else:
            most_recent_element = None
    if most_recent_element:
        result.append(most_recent_element)
    return result


Please help me to make it better.

Solution

I think you should try re-making __removepairs_once__ only using results.
No most_recent_element.

So, you would want to retry you algorithm, most_recent_element can be results[-1].
Using this you should come to this stub code:

def _remove_pairs(list_):
    result = []
    for item in list:
        if item == results[-1]:
            # remove last item
            # don't add this item
        else:
            # add this item
    return result


Using this you should notice that it'll error if results is empty, this means you should use the else if it is.
The if block is surprisingly simple, it's results.pop(). And the else is results.append(item).

def _remove_pairs(list_):
    results = []
    for item in list_:
        if results and item == results[-1]:
            results.pop()
        else:
            results.append(item)
    return results


A quick test of this actually (unsurprisingly) returns the final list that you wanted.

Don't use __{}__ for anything! Only use it for pythons magic functions!

You should also not use list but list_ as then you can still convert something to a list.

Code Snippets

def _remove_pairs(list_):
    result = []
    for item in list:
        if item == results[-1]:
            # remove last item
            # don't add this item
        else:
            # add this item
    return result
def _remove_pairs(list_):
    results = []
    for item in list_:
        if results and item == results[-1]:
            results.pop()
        else:
            results.append(item)
    return results

Context

StackExchange Code Review Q#127248, answer score: 10

Revisions (0)

No revisions yet.