Skip to content

Instantly share code, notes, and snippets.

@itrobotics
Last active October 8, 2022 06:20
Show Gist options
  • Save itrobotics/39f352a3182eecbb022bebfa183c572a to your computer and use it in GitHub Desktop.
Save itrobotics/39f352a3182eecbb022bebfa183c572a to your computer and use it in GitHub Desktop.
from collections import defaultdict
from itertools import chain
from itertools import chain, combinations
'''
Why do we use frozenset ?
Example 1:
count[{'B','C'}]+=1 # TypeError Error : "unhashable type: 'set'"
in this case, we can use frozenset to make 'set' as a key
count[frozenset({'B','C'})]=1 # OK
Example 2:
set within set
{{'A'},{'B'},{'C'}} --> TypeError: unhashable type: 'set'
we can use frozenset to achieve this
{frozenset({'A'}),frozenset({'B'}),frozenset({'C'})}
'''
count=defaultdict(int)
count[frozenset({'D'})]=0
print(count)
print('-----frozenset as a index--------')
#itemsets={frozenset({'B','C'}),frozenset({'D'})}
itemsets=[{'A','B','C'},{'D','E'}]
itemsetsList=[{'A','B','C'},{'A','B'},
{'A','B','C','D'},{'D','E'}]
for item in itemsets:
for itemset in itemsetsList:
#print('{} in {}:{}'.format(item,itemset,item.issubset(itemset)))
if item.issubset(itemset):
count[frozenset(item)]+=1 #use set as a key index
for k,v in count.items():
print(k,":",v)
print('-----frozenset with a set--------')
itemsets=[{'A','B','C'},{'A','B','E'}]
newitemsets=[]
for itemset in itemsets:
# t is a set of set
t=[set(item) for item in itemset ]
newitemsets.append(t)
print('newitemsets:',newitemsets)
print('----------')
joinset=set()
for i in newitemsets[0]: # [{'A'},{'B'},{'C'}]
for j in newitemsets[1]:# [{'D'},{'E'}]
if len(i.union(j)) == 2: # do join set with length=2
print(i.union(j))
joinset.add(frozenset(i.union(j)))
print('joinset:',joinset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment