Skip to content

Instantly share code, notes, and snippets.

@alexanderlz
Created January 21, 2014 14:19
Show Gist options
  • Save alexanderlz/8540931 to your computer and use it in GitHub Desktop.
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)
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