MA0301/exam_template/python/Powerset.py

64 lines
1.5 KiB
Python
Raw Normal View History

2021-05-17 00:33:41 +02:00
from itertools import combinations
2021-05-17 18:39:28 +02:00
from common import replaceContent
2021-05-17 00:33:41 +02:00
class Set:
def __init__(self, elements):
self.elements = set(elements)
def __str__(self):
if len(self) == 0: return "\\emptyset"
return f"\\{{ {', '.join(sorted(self.elements))} \\}}"
def __iter__(self):
return list(sorted(self.elements))
def __len__(self):
return len(self.elements)
def __gt__(self, value):
if len(self) != len(value):
return len(self) > len(value)
return self.elements > value.elements
def __ge__(self, value):
return self > value
def __lt__(self, value):
return not self > value
def __le__(self, value):
return self < value
2021-05-17 18:39:28 +02:00
@classmethod
def fromString(cls, string):
return cls(string.split(' '))
2021-05-17 00:33:41 +02:00
def cardinality(self):
return len(self)
def powerset(self):
powerset = []
for i in range(len(self) + 1):
for subset in combinations(self.elements, i):
powerset.append(Set(list(subset)))
return Set(powerset)
def to_vertical_latex(self):
column = []
for e in sorted(self.elements):
column.append(str(e) + ' \\\\')
return '\\{\n' + '\n'.join(column) + '\n\\}'
2021-05-17 18:39:28 +02:00
def processFileContent(raw):
s = Set.fromString(raw)
content = s.powerset().to_vertical_latex()
return replaceContent(content, 'Powerset')
2021-05-17 00:33:41 +02:00
#TODO: make process input func
if __name__ == "__main__":
print(Set(['a', 'b', 'c']).powerset().to_vertical_latex())
# print(a for a in Set(['A', 'B', 'C']).powerset())