2014-03-26 2 views
0

그래서 항목/항목에 대한 최소 비용 및 레스토랑 ID를 인쇄하는이 코드가 있습니다. 고객이 여러 레스토랑을 방문하고 싶지 않습니다. 예를 들어 그가 "A, B"를 묻는다면 코드는 다른 레스토랑 주변에 사용자 요구 사항을 분산시키는 대신 (둘 중 어떤 레스토랑이 값 싸게 제공하더라도) 둘 다 제공하는 상점을 인쇄해야합니다. 항목 ('햄버거'와 'D') 모두 "함께" 두 개의 레스토랑 (1 & 2)의에서 사용할 수 없기 때문에 처리 및 우회 "TypeError : 'NoneType'"파이썬 코드

오류

은 기본적으로오고있다. 그런 긴 오류를 던지기보다는 단순히 "resto에서 사용할 수없는 항목 중 하나"를 인쇄하고 싶습니다.

기타 'tofulog'는 restaurant_1에서만 사용할 수 있기 때문에 solver(shop_text,['tofulog', 'D'])입니다. '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 

====== OUTPUT ====== 오류가 requirement_one_restaurant에 있지만 당신은 단지을 게시 한 : =

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 

답변

0

역 추적 당신이 게시 한 코드와 관련하지 않는 것 0.

그러나 코드 패턴이 비슷하다고 가정하면 분명히 일종의 재귀 호출을 수행하고있는 것입니다. 이 작업을 수행 할 때 가능한 모든 경로가 값을 반환하는지 확인해야합니다. 예를 들어, 이 함수 끝까지 여전히 비어있는 경우 solve_one_shop에서 아무 것도 반환되지 않고 NoneType 오류가 발생합니다.