from itertools import combinations import clingo nhan = {"a", "b", "c"} xung_dot = [{"a", "b"}, {"b", "c"}] tap_sua = [ set(chon) for co in range(4) for chon in combinations(sorted(nhan), co) if all(set(chon) & nhom for nhom in xung_dot) ] toi_tieu = [chon for chon in tap_sua if not any(khac < chon for khac in tap_sua)] assert sorted(map(sorted, toi_tieu)) == [["a", "c"], ["b"]] ctl = clingo.Control(["0"]) ctl.add("base", [], """ nhan(a;b;c). gia(a,1). gia(b,5). gia(c,1). { bo(X) } :- nhan(X). :- not bo(a), not bo(b). :- not bo(b), not bo(c). #minimize { W,X : bo(X), gia(X,W) }. #show bo/1. """) ctl.ground([("base", [])]) nghiem = [] ctl.solve(on_model=lambda m: nghiem.append((set(map(str, m.symbols(shown=True))), list(m.cost)))) assert nghiem[-1] == ({"bo(a)", "bo(c)"}, [2]) print("Theo bao hàm", sorted(map(sorted, toi_tieu)), "| Theo chi phí", nghiem[-1])