Skip to content
Snippets Groups Projects
Commit eafff2b2 authored by maiermi's avatar maiermi
Browse files

Delete unless code

parent bf28f44d
No related branches found
No related tags found
No related merge requests found
"""
From Wikipedia:
In computer science, the subset sum problem is an important decision problem in complexity theory and cryptography. There are several equivalent formulations of the problem. One of them is: given a set (or multiset) of integers, is there a non-empty subset whose sum is zero? For example, given the set ~{−7, −3, −2, 9000, 5, 8}~, the answer is yes because the subset ~{−3, −2, 5}~ sums to zero.
[Wikipedia: Subset sum problem](https://en.wikipedia.org/wiki/Subset_sum_problem)
"""
from z3 import *
elems = [-7, -3, -2, 9000, 5, 8]
n = len(elems)
# Symbolic variables: is_in[i] is 1, if element i is in the zero sum subset, 0 otherwise
is_in = [Int(f"{i}") for i in range(n)]
# Create Z3 solver
s = Solver()
# First constraint: is_in[i] is either 0 or 1
for i in range(n):
s.add(Or(is_in[i] == 0, is_in[i] == 1))
# Second constraint: at least one element should be in the zero sum subset:
s.add(Sum(is_in) > 0)
# Third constraint: the sum of the elements in the zero sum subset should be zero:
s.add(Sum([elems[i] * is_in[i] for i in range(n)]) == 0)
# Check satisfiability and print solution if found
if s.check() == sat:
print([elems[i] for i in range(n) if s.model().eval(is_in[i], model_completion=True) == 1])
else:
print("Unsatisfiable!")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment