所以我有這個代碼打印出項目/項目的最低成本和餐館ID。客戶不想訪問多家餐館。例如,如果他要求「A,B」,那麼代碼應該打印提供這兩者的商店,而不是將用戶需求分散在不同的餐館周圍(即使一些餐館提供便宜)。在Python代碼中處理和繞過「TypeError:'NoneType'」
的誤差基本進入,因爲無論是項(「漢堡」和「d」)不提供「一起」在任何兩個餐館(1 & 2)的。但是,我不想扔這麼長的錯誤,我只想打印「其中一個項目不可用於恢復」等。
其他此類錯誤引發的協議是solver(shop_text,['tofulog', 'D'])
,因爲'tofulog'僅在restaurant_1,wheras 'D'只能在restaurant_2上使用。
def build_shops(shop_text):
shops = {}
for item_info in shop_text:
shop_id,cost,items = item_info.replace('\n', '').split(',')
cost = float(cost)
items = items.split('+')
if shop_id not in shops:
shops[shop_id] = {}
shop_dict = shops[shop_id]
for item in items:
if item not in shop_dict:
shop_dict[item] = []
shop_dict[item].append([cost,items])
return shops
def solve_one_shop(shop, items):
if len(items) == 0:
return [0.0, []]
all_possible = []
first_item = items[0]
if first_item in shop:
for (price,combo) in shop[first_item]:
#print "items,combo=",items,combo
sub_set = [x for x in items if x not in combo]
#print "sub_set=",sub_set
price_sub_set,solution = solve_one_shop(shop, sub_set)
solution.append([price,combo])
all_possible.append([price+price_sub_set, solution])
if all_possible:
cheapest = min(all_possible, key=(lambda x: x[0]))
return cheapest
def solver(input_data, required_items):
shops = build_shops(input_data)
result_all_shops = []
for shop_id,shop_info in shops.iteritems():
this_shop = solve_one_shop(shop_info, required_items)
if this_shop is not None:
(price, solution) = this_shop
result_all_shops.append([shop_id, price, solution])
shop_id,total_price,solution = min(result_all_shops, key=(lambda x: x[1]))
print('SHOP_ID=%s' % shop_id)
sln_str = [','.join(items)+'(%0.2f)'%price for (price,items) in solution]
sln_str = '+'.join(sln_str)
print(sln_str + ' = %0.2f' % total_price)
shop_text = open('input-1.csv','rb')
solver(shop_text,['burger', 'D'])
=====輸入1.csv ===== restaurant_id,價格,項目
1,2.00,burger
1,1.25,tofulog
1,2.00,tofulog
1,1.00,chef_salad
1,1.00,A+B
1,1.50,A+CCC
1,2.50,A
2,3.00,A
2,1.00,B
2,1.20,CCC
2,1.25,D
======輸出====== =
Traceback (most recent call last):
File "26mar_cheap.py", line 106, in <module>
final_out(restaurant_read,sys.argv[2:])
File "26mar_cheap.py", line 92, in final_out
this_resto = requirement_one_restaurant(shop_info, required_items)
File "26mar_cheap.py", line 77, in requirement_one_restaurant
cost_sub_set,solution = requirement_one_restaurant(shop, sub_set)
TypeError: 'NoneType' object is not iterable