《算法图解》第八章 贪婪算法 示例

今天刚看到这一个示例,但是运行时结果中出现None。改了一下格式,出现了正确结果:

states_needed=set(['mt','wa','or','id','nv','ut','ca','az']) #传入一个数组,它被转换为集合  州

stations={} #广播台清单
stations['kone']=set(['id','nv','ut'])
stations['ktwo']=set(['wa','id','mt'])
stations['kthree']=set(['or','nv','ca'])
stations['kfour']=set(['nv','ut'])
stations['kfive']=set(['ca','az'])

final_station=set() #最终选择的广播台

while states_needed:
    best_station=None
    states_covered=set()
    for station,states_for_station in stations.items():
        '''
        print(station)
        print('*station*')
        print(states_for_station)
        print('*states_for_station*')
        '''
        covered=states_needed & states_for_station #计算交集
        if len(covered) > len(states_covered):
            best_station=station
            states_covered=covered
            #这个地方书上的格式有问题        
            states_needed-=states_covered
            final_station.add(best_station)
print(final_station)

明天仔细看这个案例。

猜你喜欢

转载自blog.csdn.net/qq_41109499/article/details/84332552