Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get rid of repeated self values and keep only one out of (2,0) (0,2)?

according to @KellyBundy answer, I’d like to get rid of repeated self-values (2, 2), (0, 0)
and keep only either (2, 1) or (1, 2), keep only either (1, 0) or (0, 1) and get rid of repeated (0, 2)

 [(0, 2), (2, 2), (2, 1), (1, 2), (2, 2), (0,2),  (2, 2), (2, 1), (1, 0), (0, 0), (0, 1)]

out of this
from itertools import pairwise, chain

lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]

found = [*chain(*(pairwise(a) for *a, a[1:] in lis))]

print(found)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

mylist =  [(0, 2), (2, 2), (2, 1), (1, 2), (2, 2), (0,2),  (2, 2), (2, 1), (1, 0), (0, 0), (0, 1)]
seen = set()
final = [(i,j) for i,j in mylist if i!=j and (i+j, abs(i-j)) not in seen and not seen.add((i+j, abs(i-j)))]

we filter on ((i+j), abs(i-j))

if you really need a one liner, we can use a lambda function

list(filter(lambda e, seen=set(): e[0]!=e[1] and (e[0]+e[1], abs(e[0]-e[1])) not in seen and not seen.add((e[0]+e[1], abs(e[0]-e[1]))), mylist))

i+j and abs(i-j) here are the sum and absolute difference. It makes the logic simpler since (x,y) and (y,x) have the same absolute difference and the same sum.
(i+j, abs(i+j)) is a tuple containing both the sum and absolute difference

seen here is a python set, which can be used to efficiently check if something already exists within it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading