Skip to content

Instantly share code, notes, and snippets.

@maxdeleon
Created March 29, 2022 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxdeleon/d94c4e8a5c132d26d4a4caf3aabaed46 to your computer and use it in GitHub Desktop.
Save maxdeleon/d94c4e8a5c132d26d4a4caf3aabaed46 to your computer and use it in GitHub Desktop.
Makes a power set provided a set using
# Maximo Xavier deLeon 03/28/2022
# Makes a power set provided a set
def removeDuplciates(l):
nl=list()
for i in l:
if i not in nl:
nl.append(i)
return nl
def main():
# define origional set and remove duplicates if they exist
originalSet = removeDuplciates(['a','b','c','c'])
# define integer k and power set
k = len(originalSet)
powerSet = list()
# iterate 2**k times by definition the cardinality of a power set
for i in range(2**k):
# create binary index for list comprehension
subset_index = [int(i) for i in str('{0:b}'.format(i,"b"))]
subset_index = [0]*(k-len(subset_index)) + subset_index
# list comprehension to generate list of elements determined by binary number index
subset = [originalSet[j-k] if subset_index[j-k] == 1 else None for j in range(k)]
# remove the None values and append power set
subset = list(filter(None, subset))
powerSet.append(subset)
#print out stuff
print('A: {}\nP(A): {}\n{}'.format(originalSet,powerSet,'='*10))
print('|A|: {}\n|P(A)|: {}'.format(k,2**k))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment