looking for some solutions? You are welcome.

SOLVED: Remove unnecessary items from python list


I have a list of 8 unique tuples, each of size 2. From there I find all possible combinations of size 4. Now, I have a list of lists, and in each of the sublists I have exactly 4 tuples. Something like -

[[(1, 2), (4, 5), (223, 456), (111, 345)], [...], ...]

Where the main list maybe -

[(1, 2), (4, 5), (223, 456), (111, 345), (123, 4), (23, 89), (999, 888), (895, 569)]

These are actually co-ordinates of points in a 2D plane and I am dividing the 8 points in two sets of 4 each. So if I have a list of 4 points, it means I already have the other four points as well. So for every combination of 4 points I am trying to remove the other 4 points from the list.

The following works -

def generate_all_points(points, size):
    from itertools import combinations

    all_combinations = combinations(points, size)
    return (list(all_combinations))    

def generate_4points(points):

    all_4points = generate_all_points(points, 4)
    print (len(all_4points))
    print ("ALL POINTS -\t", points)
    for point_set in all_4points:

        to_remove = list(set(points).difference(set(point_set)))
        for item in all_4points:
            if (len(set(to_remove).difference(item)) == 0):

        print ("Main -\t", point_set, "\nTo Remove -\t", to_remove)
    print (len(all_4points))

I tried using just the set.difference but it reorders the list items and thus I can't remove them directly. That I tried in the commented line. What I did was find the remaining 4 points from the 8, then if the length of the set difference of the 4 and any item in the list of combinations is zero, then that means together, both set of 4 points match up to the unique 8, thus I remove that particular item.

Is there a way to directly achieve this maybe in one or two lines without loops and such?

Thanks in advance.

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots

No comments: