Add the empty set to a family of sets in a frozenset in python

天大地大妈咪最大 提交于 2019-12-11 04:48:20

问题


Suppose I generate a frozenset with

A = frozenset(frozenset([element]) for element in [1,2,3])

And I have the empty set

E = frozenset(frozenset())

Now I want to have the union of both sets:

U = A | E

This gives me

frozenset({frozenset({2}), frozenset({3}), frozenset({1})})

this assumes, that a frozenset, containing an empty frozenset is itself empty. However, I'd like to have

frozenset({frozenset({}), frozenset({2}), frozenset({3}), frozenset({1})})

So, I'd like to add the empty set explicitly to the set. This is, for example, necessary in my opinion when constructing a power set?

So: Is a family of sets that only contains the empty set itself empty? Is there a way, in Python, to explicitly include an empty set into a family of sets using the variable types set and frozenset?


回答1:


E is an empty set, with no elements:

>>> frozenset(frozenset())
frozenset()

That's because the argument to fronenset() is an iterable of values to add. frozenset() is an empty iterable, so nothing is added.

If you expected E to be a set with one element, you need to pass in an iterable with one element; use {...} set notation, or a single element tuple (...,), or a list [...]:

>>> frozenset({frozenset()})  # pass in a set() with one element.
frozenset({frozenset()})

Now you get your expected output:

>>> A = frozenset(frozenset([element]) for element in [1,2,3])
>>> E = frozenset({frozenset()})
>>> A | E
frozenset({frozenset({3}), frozenset({2}), frozenset({1}), frozenset()})


来源:https://stackoverflow.com/questions/50389974/add-the-empty-set-to-a-family-of-sets-in-a-frozenset-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!