Skip to content

Instantly share code, notes, and snippets.

@mahanmarwat
Last active August 29, 2015 14:05
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 mahanmarwat/f5dc8d8f9a54d67d3354 to your computer and use it in GitHub Desktop.
Save mahanmarwat/f5dc8d8f9a54d67d3354 to your computer and use it in GitHub Desktop.
Solution to "picking the most valueable things" problem.
# Python 3.4
# Author: Mahan Marwat
from itertools import combinations
items = {'Clock': [175, 10],
'Painting': [90, 9],
'Radio': [20, 4],
'Vase': [50, 2],
'Book': [10, 1],
'Computer': [200, 20]
}
def most_valuable(items):
total_comb = []
for i in range(1, (len(items) + 1)):
total_comb.append(list(combinations(items, i)))
total_comb_with_values = []
for comb in total_comb:
for child_comb in comb:
value = 0
weight = 0
items_with_values = []
for item in child_comb:
items_with_values.append(item)
value += items[item][0]
weight += items[item][1]
items_with_values.extend([value, weight])
total_comb_with_values.append(items_with_values)
return total_comb_with_values
def burglar(items):
most_valuable_value = 0
most_valuable = None
for item in items:
if item[-1] > 20: continue
if item[-2] > most_valuable_value:
most_valuable_value = item[-2]
most_valuable = item
return most_valuable
if __name__ == '__main__':
valuable = burglar(most_valuable(items))
print('Hurra...!')
print('"Your money, or your life. We know what to do when a burglar makes\n this demand of us, but not when God does." ―Mignon McLaughlin')
print('I am going with: {0} and {1}'.format(', '.join(
[item for item in valuable[:-3]]), valuable[-3]))
print('Value: {0}, Weight: {1}'.format(*valuable[-2:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment