代码之家  ›  专栏  ›  技术社区  ›  Vondoe79

Python:如何对优化问题的解决方案进行编码

  •  0
  • Vondoe79  · 技术社区  · 7 年前

    请让我知道,如果你需要进一步澄清我的逻辑在插入部分。

    ####____BELOW CODE is being designed encode a solution for a GA_____#
    populationSize = 1 (this will be varied)
    num_salesmen = 2
    population_list = [[4, 2, 3], [0, 1, 0], [1, 0], [1, 0]]
    
        ## - where [4, 2, 3] is a list of cities to be visited by salesmen, 
        ## - [0, 1, 0] the list of salesman, and 
        ## - [1, 0], [1, 0] are the lists of starting and ending depots of the 
              salesman one (0) and salesman two (1) respectively.
    
    for pop in population_list:  
        ##----Part ONE: determine cities assigned to each salesman:
        Assigned_cites = [[] for x in range(num_salesmen)]
        for i in range(len(pop[1])):
            for man in range(num_salesmen):
                if pop[1][i] == man:
                   Assigned_cites[man].append(pop[0][i])
    
    ##---- Part TWO: inserting the starting and ending depots: 
    for s_man in range(num_salesmen):
        for s_e_d in range(2,num_salesmen+2):         
            Assigned_cites[s_man].insert(0,pop[s_e_d][0])
            Assigned_cites[s_man].append(pop[s_e_d][1])
    
        ###- expected result from Part TWO Should look like below, but I am not getting it:
           [[1, 4, 3, 0], [1, 2, 0]]
    

    事先谢谢你的帮助。

    1 回复  |  直到 7 年前
        1
  •  0
  •   perseverance    7 年前
    #your extraction logic need a bit of tweaking    
    Assigned_cites = [[] for x in range(num_salesmen)]
        for i in range(len(population_list[1])):
            for man in range(num_salesmen):
                if population_list[1][i] == man:
                   Assigned_cites[man].append(population_list[0][i])
        print Assigned_cites
        s_man = 0 # no need of an outer for loop for sales man
        for s_e_d in range(2,num_salesmen+2):         
            Assigned_cites[s_man].insert(0,population_list[s_e_d][0])
            Assigned_cites[s_man].append(population_list[s_e_d][1])
            s_man = s_man + 1
        print Assigned_cites