Skip to content

Instantly share code, notes, and snippets.

@hroncok
Last active January 27, 2016 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hroncok/0a3c9f1c9c4baf5f716c to your computer and use it in GitHub Desktop.
Save hroncok/0a3c9f1c9c4baf5f716c to your computer and use it in GitHub Desktop.
# TABLE je ve skutečnosti instanční proměnná, ale berte to, jakože je globální
def solve():
TABLE = {} # slovník/hash kde klíče budou dvojice
for cost in MAX_COST..0:
weight, combo = _solve(NUMITEMS, cost)
if weight <= CAPACITY:
maxcombo = combo
maxcost = cost
return maxcombo, maxcost
def _solve(index, cost):
if index == 0:
if cost == 0:
return 0, [False] * NUMITEMS
return float('inf'), [True] * NUMITEMS # whatever, tudy IMHO nikdy nepůjdem
try:
return TABLE[(index, cost)]
except KeyError:
index -= 1
lesscost = cost - ITEMS[index]['cost']
addweight = ITEMS[index]['weight']
skip, skipstate = _solve(index, cost)
add, addstate = _solve(index, lesscost)
if skip < add + addweight:
TABLE[(index + 1, cost)] = skip, skipstate.copy()
else
addstate = addstate.copy()
addstate[index] = True
TABLE[(index + 1, cost)] = add + addweight, addstate
return TABLE[(index + 1, cost)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment