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.