Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
Z
zerosumset4
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Package Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Anna Postnikova
zerosumset4
Commits
a224a1e3
Commit
a224a1e3
authored
3 years ago
by
Michael Maier
Browse files
Options
Downloads
Plain Diff
Merge branch 'master' of mygit.th-deg.de:ap04811/zerosumset
parents
d363eaa4
7a83e70c
No related branches found
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
zerosumset/__init__.py
+46
-0
46 additions, 0 deletions
zerosumset/__init__.py
with
46 additions
and
0 deletions
zerosumset/__init__.py
+
46
−
0
View file @
a224a1e3
...
...
@@ -43,3 +43,49 @@ def zerosumset(elems):
return
[]
def
maxzerosumset
(
elems
):
"""
>>>
from
z3
import
*
>>>
zerosumset
([
1
,
500
,
-
1
])
[
1
,
-
1
]
>>>
zerosumset
([
8
,
-
7
,
-
1
,
20
])
[
8
,
-
7
,
-
1
]
>>>
zerosumset
([
50
,
-
3
,
4
,
2
,
1
])
[
-
3
,
2
,
1
]
>>>
zerosumset
([
1
,
2
,
3
])
[]
>>>
zerosumset
([])
[]
"""
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 optimizer
s
=
Optimize
()
# 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)
# is replaced by computing the number of elements in the sublist
sublist_len
=
Int
(
'
sublist_len
'
)
s
.
add
(
sublist_len
==
Sum
(
is_in
))
# 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
)
s
.
maximize
(
sublist_len
)
# Check satisfiability and print solution if found
if
s
.
check
()
==
sat
:
result
=
[
elems
[
i
]
for
i
in
range
(
n
)
if
s
.
model
().
eval
(
is_in
[
i
],
model_completion
=
True
)
==
1
]
else
:
result
=
[]
return
result
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment