Created
January 21, 2014 14:19
-
-
Save alexanderlz/8540931 to your computer and use it in GitHub Desktop.
greedy set cover implementation (lurk more here http://en.wikipedia.org/wiki/Set_cover_problem) targetSet - the set you want to cover
subSets - dictionary of subsets to cover the target set (uncomment the "#result" in case you want to see the resulting set also)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def greedySetCover(targetSet, subSets): | |
if not subSets: | |
return None | |
probeKey = max(subSets, key=lambda x: len(targetSet.intersection(subSets[x]))) | |
probeSet = subSets[probeKey] | |
#result = set() | |
resKeys = set() | |
while len(targetSet) > 0: | |
#result.update(probeSet) | |
targetSet = targetSet.difference(probeSet) | |
resKeys.add(probeKey) | |
del(subSets[probeKey]) | |
if subSets: | |
probeKey = max(subSets, key=lambda x: len(targetSet.intersection(subSets[x]))) | |
probeSet = subSets[probeKey] | |
if len(targetSet.intersection(probeSet)) == 0: | |
break | |
else: | |
break | |
#return result, resKeys | |
return resKeys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment