【发布时间】:2019-05-09 01:19:19
【问题描述】:
所以我有一个商店列表及其库存和购物清单。我需要找到满足购物清单的最少商店数量。我目前已将商店名称分开以创建商店的所有排列。我不确定如何实际将商店库存与我拥有的购物清单进行比较。任何帮助将不胜感激。
def satisfy_shopping_list(shopping_list_json, inventory_json):
# find out minimum combination of stores that would satisfy shopping list
shops = []
print(inventory_json['stores'])
for item in inventory_json['stores']:
shops.append(item.get("name"))
routes = list(itertools.permutations(shops))
print(routes)
# if shopping list is impossible to satisfy
shopping_list_satisfiable = True
if shopping_list_satisfiable:
# print out number of stores and corresponding combinations
# num_stores = 0
# print "The shopping list can be satisfied by visiting {} store(s):".format(num_stores)
# for each valid store_combination:
# print_store_list(store_combination)
pass
else:
print("No combination of given stores can satisfy this shopping list :(")
pass
def print_store_combination(store_combination):
store_combination_copy = copy.deepcopy(store_combination)
store_combination_copy.sort()
print(', '.join(store_combination_copy))
def main():
args = parse_args()
with open(args.shopping_list_json_path) as shopping_list_json_file, open(args.inventory_json_path) as inventory_json_file:
shopping_list_json = json.load(shopping_list_json_file)
inventory_json = json.load(inventory_json_file)
satisfy_shopping_list(shopping_list_json, inventory_json)
def parse_args():
p = argparse.ArgumentParser()
p.add_argument('shopping_list_json_path')
p.add_argument('inventory_json_path')
args = p.parse_args()
return args
if __name__ == '__main__':
main()
购物清单示例
{
"apples": 10,
"oranges": 10,
"pineapples": 10,
"coconuts": 10,
"strawberries": 10,
"peaches": 1
}
库存示例
{
"stores": [
{
"name":"Kroger",
"inventory": {
"oranges": 10,
"coconuts": 10,
"strawberries": 10
}
},
{
"name":"Meijer",
"inventory": {
"oranges": 10,
"grapes": 10,
"pineapples": 10,
"strawberries": 10
}
},
{
"name":"Store 3",
"inventory": {
"apples": 1,
"oranges": 10,
"bananas": 10,
"grapes": 10,
"chickens": 10
}
},
{
"name":"Whole Foods",
"inventory": {
"grapes": 10,
"pineapples": 10,
"organic apples": 10,
"coconuts": 10,
"strawberries": 10
}
},
{
"name":"Kroger 2",
"inventory": {
"apples": 8
}
},
{
"name":"peach store",
"inventory": {
"peaches": 1
}
},
{
"name":"CVS",
"inventory": {}
},
{
"name":"apples r us",
"inventory": {
"apples": 10000000000000
}
}
]
}
【问题讨论】:
-
所以您想知道您必须访问多少家商店才能满足您的购物清单需求?
-
@aws_apprentice 是的
-
我们可以为您提供一个简单的解决方案,但这是一个旅行商问题的变体,很难正确解决
-
@aws_apprentice 那太好了
-
所以你不在乎这是否是一个幼稚的解决方案?
标签: python python-3.x