exercise6.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from z3 import *
  2. def all_smt(s, initial_terms):
  3. def block_term(s, m, t):
  4. s.add(t != m.eval(t, model_completion=True))
  5. def fix_term(s, m, t):
  6. s.add(t == m.eval(t, model_completion=True))
  7. def all_smt_rec(terms):
  8. if sat == s.check():
  9. m = s.model()
  10. yield m
  11. for i in range(len(terms)):
  12. s.push()
  13. block_term(s, m, terms[i])
  14. for j in range(i):
  15. fix_term(s, m, terms[j])
  16. yield from all_smt_rec(terms[i:])
  17. s.pop()
  18. yield from all_smt_rec(list(initial_terms))
  19. def main():
  20. s = Solver()
  21. for n in range(2, 5):
  22. s.push()
  23. left = [Int(str(i)) for i in range(n)]
  24. right = [Int(str(i + n)) for i in range(n)]
  25. # constrain size of number to have the right number of digits
  26. sum_l = 0
  27. sum_r = 0
  28. for i in range(n):
  29. s.add(left[i] >= 0, left[i] < 10)
  30. s.add(right[i] >= 0, right[i] < 10)
  31. sum_l += left[i]
  32. sum_r += right[i]
  33. s.add(sum_l == sum_r)
  34. models = list(all_smt(s, left + right))
  35. print(f'for n={n} there are {len(models)} models')
  36. #print(f'here are 10 models: {models[:10]}')
  37. s.pop()
  38. if __name__ == '__main__':
  39. main()