pythonsetset-comprehension

How to add pairs of elements in Python set comprehension depending on boolean statement?


I have a frozenset of three elements F = {v0,v1,v2} and a set of frozensets of two elements, i.e., E = {e0,e1,e2,...} where each ei=frozenset({x,y}). I want to find the following set

S = {frozenset({a,b}) : a,b in E, a and b each contain distinct elements of F, and a and b share an element}.

ex: a contains v0, b contains v1, and a and b both contain v7 (some arbitrary value not in F) means frozenset({a,b}) is in S.

Can I do this with a one line set comprehension?

For context, I am trying to write a script to refine an octahedron triangulation as shown in the picture:

algorithm

the set S I'm after would be the green text.

So far I have the following:

import pylab as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

### Initial octahedron ###

Vertices = [ [0,0,1], [1,0,0], [0,1,0], [-1,0,0], [0,-1,0], [0,0,-1] ]
Edges = { frozenset({0,1}), frozenset({0,2}), frozenset({0,3}), frozenset({0,4}),
          frozenset({1,2}), frozenset({2,3}), frozenset({3,4}), frozenset({1,4}),
          frozenset({1,5}), frozenset({2,5}), frozenset({3,5}), frozenset({4,5}) }
Faces = { frozenset({0,1,2}), frozenset({0,2,3}), frozenset({0,3,4}), frozenset({0,1,4}),
          frozenset({1,2,5}), frozenset({2,3,5}), frozenset({3,4,5}), frozenset({1,4,5}) }

### New set of vertices, edges, and faces ###

counter=5

newVertices=set()
newEdges=set()
newFaces=set()

for edge in Edges: # adding elements of newVertices and newEdges
    counter=counter+1
    newVertices.add(counter)
    for vertex in edge:
        newEdges.add(frozenset({vertex,counter}))

Solution

  • IIUC you can do:

    from itertools import combinations
    
    F = {1, 2, 3}
    E = {frozenset([1, 2]), frozenset([2, 3]), frozenset([3, 4]), frozenset([3, 5])}
    
    print([(a, b) for a, b in combinations({s for s in E if s - F}, 2) if a & b])
    

    Prints:

    [(frozenset({3, 4}), frozenset({3, 5}))]
    

    Explanation:

    With:

    F = {1, 2, 3}
    E = {frozenset([1, 2]), frozenset([2, 3]), frozenset([3, 4]), frozenset([3, 5])}
    

    I'm trying to find combination of two frozensets from set E that share common element and have some element distinct from elements in F