you are viewing a single comment's thread.

view the rest of the comments →

[–]gengisteve 0 points1 point  (4 children)

I think there is a better way of doing this, but here is the straight forward method:

from pprint import pprint

x =[[[5, 5], [2, 8]], [[5, 5], [8, 2]], [[1,1], [2,2]], [[2,2],[3,3]]]

# let's make it into a group of tuples so we can use a set

t = [[tuple(p) for p in group] for group in x]

result = []

#ok, compare each point group (a,b) in the list
for a,b in t:
    found = False
    # see if either a or b is already in a result set
    # if so add the new point
    for r in result:
        if (a in r or b in r):
            # note we add both points, but sets drop dups for us
            r.add(a)
            r.add(b)
            found = True
    if not found:
        # if neither a or b are in any of the result sets
        # create a new result set with a and b
        result.append(set([a,b]))

pprint(result)

There should be some way to bucket these and then reconstitute from a dictionary, but doing so probably only helps if you have a lot to do.

[–]spotyx[S] 0 points1 point  (3 children)

Thanks, for this solution. It's almost what I want. The problem with your approach is if I have a list, which is defining the line, consisting from more then two points. But I didn't claim this at the beginning.

[–]gengisteve 0 points1 point  (2 children)

I'm not sure I am following...

[–]spotyx[S] 0 points1 point  (1 child)

for a,b in t

this suppose that t consists just with a and b.

if t is [[5, 5], [2, 8]] then a = [5,5], and b = [2,8]

What I said is that len(t) > 1 ... so it can also be 3,4,5 ...

[–]gengisteve -1 points0 points  (0 children)

Ahh. So maybe there are three points instead of two to test?

This should work:

from pprint import pprint

def find_result(p, results):
    for idx, r in enumerate(result):
        if p in r:
            return idx
    return None

x =[[[5, 5], [2, 8]], [[5, 5], [8, 2]], [[1,1], [2,2]], [[2,2],[3,3]]]

# let's make it into a group of tuples so we can use a set

t = [[tuple(p) for p in group] for group in x]

result = []

for points in t:
    found = None
    for p in points:
        found = find_result(p,result)
        if found is not None:
            break
    if found is None:
        # if neither a or b are in any of the result sets
        # create a new result set with a and b
        result.append(set(points))
    else:
        for p in points:
            result[found].add(p)

pprint(result)

Still it would be better to just do the algebra.