Skip to content

Instantly share code, notes, and snippets.

@USM-F
Last active February 15, 2020 11:47
Show Gist options
  • Save USM-F/02485a028be99a1aea2e9eb0d5e8ce5a to your computer and use it in GitHub Desktop.
Save USM-F/02485a028be99a1aea2e9eb0d5e8ce5a to your computer and use it in GitHub Desktop.
Simple recursive solver for set cover problem
from collections import Counter
def set_cover_recursive(sets, result, element_index=0, prefix=[]):
if len(prefix)==len(sets[0]):
result.append(prefix)
return True
# Check validity of allocation
for i in range(len(sets)):
if sets[i][element_index] == 1:
set_cover_recursive(sets, result, element_index+1, prefix+[i])
def get_optimal_sets(sets, solutions):
optimal = []
minimal = len(sets)
for solution in solutions:
if len(Counter(solution))<minimal:
optimal.clear()
minimal = len(Counter(solution))
optimal.append(solution)
elif len(Counter(solution))==minimal:
optimal.append(solution)
return (optimal, minimal)
def set_cover(sets):
result = []
set_cover_recursive(sets, result)
return get_optimal_sets(sets, result)
#Example
sets = [
#el0 el1 el2
[1, 0, 0], #set_0
[0, 1, 1], #set_1
[1, 0, 1] #set_2
]
set_cover(sets)
#answer ([[0, 1, 1], [2, 1, 1], [2, 1, 2]], 2) means that optimal quantity of sets are 2 and there are three identical solutions
#[0, 1, 1] means that el0 in set_0, el1, el2 in set_1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment