example from chapter 8. Greedy algorithms. Essence - enumerates all the sets. finds intersection. I can not understand how final_station.add (best_station) works? when the interpreter is started, there is always a different answer. If instead of add I write append and remove set. all OK.

states_needed=set(["mt","wa","or","id","nv","ut","ca","az"]) stations ={} stations["kone"]=set(["id","nv","ut"]) stations["ktwo"]=set(["id","wa","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 state_covered=set() for station,state in stations.items(): covered=states_needed & state if len(covered)>len(state_covered): best_station=station state_covered=covered final_station.add (best_station) states_needed-=state_covered print( final_station) 

    1 answer 1

    The set is an unordered object. In this connection, the order of elements is random. Unlike the list where the order is observed.

    • one
      I correctly understood that the operation add adds an element to the set where all these elements are in random order. because the print prints them always differently? - Alex
    • one
      Initially, choosing a set for storage, you should understand for yourself that when calling, the order of elements will be random. And yet, the set does not have the append() method, and the list has no add() method - Andrey
    • @Alex, yes, I understood correctly. However, there are also ordered dictionaries if they are very necessary. import collections and define the dictionary like this: d = collections.OrderedDict() . Then everything will always be in order). In addition, you can use Index from the Pandas module ... It also behaves like an ordered dictionary .. - Vasyl Kolomiets