" " :
import itertools
toks = 12, 11, 8, 7, 6, 2, 1
cont = {12: set([11, 8, 7, 2]),
11: set([8, 7, 6]),
7: set([2]),
2: set([1]),
}
rec_calls = 0
def bestgroup(toks, contdict, arein=(), contset=()):
"""Recursively compute the highest-valued non-contradictory subset of toks."""
global rec_calls
toks = list(toks)
while toks:
toptok = toks.pop(0)
if toptok in contset:
continue
without_top = bestgroup(toks, contdict, arein, contset)
contset = set(contset).union(c for c in contdict.get(toptok, ()))
newarein = arein + (toptok,)
with_top = bestgroup(toks, contdict, newarein, contset)
rec_calls += 1
if sum(with_top) > sum(without_top):
return with_top
else:
return without_top
return arein
def noncongroups(toks, contdict):
"""Count possible, non-contradictory subsets of toks."""
tot = 0
for l in range(1, len(toks) + 1):
for c in itertools.combinations(toks, l):
if any(cont[k].intersection(c) for k in c if k in contdict): continue
tot += 1
return tot
print bestgroup(toks, cont)
print 'calls: %d (vs %d of %d)' % (rec_calls, noncongroups(toks, cont), 2**len(toks))
, , () , ( , - noncongroups, , , , ; -).
" ", - ( , , , , - ;-) ( ). , , ( , , , , - , , , ).