I am working on an optimization problem and needed to encode the solution to the problem. Below is the piece of code I wrote for this task. Part one of the extracts the corresponding cities assigned to each salesman. In Part two of the code, I want to insert the starting and ending depots (cities) of each of the salesmen. I want this process to be dynamic as the starting/ending depots lists will change as the "num_salesmen" variable changes. The "population_list" will hold members of the population. I have given one example to aid in your assistance of this request.
Please let me know if you need further clarification of my logic in the inserting part.
####____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]]
Thanks in advance for your help.
#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
Related
list1 = [[1,2,3],[4,5,6],[7,8,9]]
Is there anyway possible in the realm of coding that I can permutate this list of lists while keeping the "groups" together?
I really need this solved, been working on a code all week and this is like the last step.
Result should look something like this or close:
permuations_list1 = [[2,3,1],[6,5,4],[8,9,7]], [[3,2,1],[4,5,6],[8,7,9]], .......
I have searched over alot of sites for a solution, but none of them keep the original lists grouped together. Anything helps.
This problem can be split into two steps:
Generate all permutations for each sublist
Generate all unique combinations of (perm_X_of_sublist_1, perm_Y_of_sublist_2, perm_Z_of_sublist_3)
In python, a working solution would look like this:
import itertools
# step 1 - generate all permutations for each sublist
permutated_sublists = (itertools.permutations(sublist) for sublist in list1)
# step 2 - generate a cartesian product of permutated sublists and gather results
permutations_list = list(itertools.product(*permutated_sublists))
The result will look like this
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
[[1, 2, 3], [4, 5, 6], [7, 9, 8]],
[[1, 2, 3], [4, 5, 6], [8, 7, 9]],
... (212 more combinations)
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]]
I have got some code from git and i was trying to understand it, here's a part of it, i didn't understand the second line of this code
G = nx.Graph(network_map) # Graph for the whole network
components = list(nx.connected_components(G))
Whats does this function connected_components do? I went through the documentation and couldn't understand it properly.
nx.connected_components(G) will return "A generator of sets of nodes, one for each component of G". A generator in Python allows iterating over values in a lazy manner (i.e., will generate the next item only when necessary).
The documentation provides the following example:
>>> import networkx as nx
>>> G = nx.path_graph(4)
>>> nx.add_path(G, [10, 11, 12])
>>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
[4, 3]
Let's go through it:
G = nx.path_graph(4) - create the directed graph 0 -> 1 -> 2 -> 3
nx.add_path(G, [10, 11, 12]) - add to G: 10 -> 11 -> 12
So, now G is a graph with 2 connected components.
[len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)] - list the sizes of all connected components in G from the largest to smallest. The result is [4, 3] since {0, 1, 2, 3} is of size 4 and {10, 11, 12} is of size 3.
So just to recap - the result is a generator (lazy iterator) over all connected components in G, where each connected component is simply a set of nodes.
I'm struggling to think about how to achieve this. What I want to do is have a series of questions (to represent a Likert table) in a CharField object like so:
for a in range(1, 11):
locals()['ATL' + str(a)] = models.PositiveIntegerField(
choices=[
[1, 'Disagree Completely'],
[2, 'Disagree Strongly'],
[3, 'Disagree'],
[4, 'Neutral'],
[5, 'Agree'],
[5, 'Agree Strongly'],
[7, 'Agree Completely'],
],
widget=widgets.RadioSelectHorizontal(),
verbose_name = Constants.ATL_qu_list[a-1])
del a
And then change the verbose name for the question depending on the question number (again, I know I'm not supposed to be using locals() to store variables). Is there an easier way of achieving a dynamic label though? Thanks!
Okay, here's my answer (as well as a clarification for what I am looking for). Basically I had a series of Likert questions to put to participants which I wanted to represent as CharFields. Because each Likert question uses the same seven choice scale, it seems like inefficient coding to repeat the same functionality and only change the verbose name between each declaration.
Accordingly, I've instead used this method to achieve what I want:
# Reads in the list of survey questions
with open('survey/survey_questions.csv') as csvfile:
data_read = list(csv.reader(csvfile))
...
for a in range(1, 11):
locals()['ATL' + str(a)] = models.PositiveIntegerField(
choices=[
[1, 'Disagree Completely'],
[2, 'Disagree Strongly'],
[3, 'Disagree'],
[4, 'Neutral'],
[5, 'Agree'],
[6, 'Agree Strongly'],
[7, 'Agree Completely'],
],
widget=widgets.RadioSelectHorizontal(),
verbose_name = data_read[a-1][0])
del a
I once saw a transformation (a cousin of RLE, delta encoding, and other number based, 1D lossless transformation meant to help the Huffman compression) which was based on a recursive mean / delta operations.
example:
[3, 5] -> [4, +1]
where
4 = (3+5)/2 # the average value
4 - 1 = 3 = # the delta reconstruction
4 + 1 = 5
And the process was applied recursively... Maybe something like :
[3, 5, 4, 6] -> [4, +1, 5, +1] -> [4, 5, +1, +1] -> [4.5, +0.5, 1, +0] etc.
But I can't remember how, since I lost its name, hence I can't google it. Does it ring a bell to someone ?
It's mid / side encoding. Usually audio compressors use it to increase compression ratio for stereo audio. For example, Monkey's Audio compressor use it as pointed out in its documentation: http://www.monkeysaudio.com/theory.html
First, sorry for my bad english, this problem is not trivial to explain so I hope you will understand me.
I have 2 models as the following:
class A(models.Model):
code = models.CharField(unique=True, max_length=10)
list_of_b = models.ManyToManyField('B')
class B(models.Model):
code = models.CharField(unique=True, max_length=10)
I aim to retrieve instances of A which match exactly with a given list of B ids.
For example, imagine I have the following records of A in my database:
id: 1 - code: X - list_of_b: [1, 2, 4, 6]
id: 2 - code: Y - list_of_b: [2, 5, 6]
id: 3 - code: Z - list_of_b: [2, 3, 4, 5, 6]
With [2, 5, 6] as given list, I should retrieve the record 2 and 3, not 1.
I succeed to retrieve records with an exact match of ids with this query:
queryset = A.objects.prefetch_related('list_of_b')
queryset = queryset.annotate(nb=Count('list_of_b')).filter(nb=len(my_list))
for id in my_list:
queryset = queryset.filter(list_of_b=id)
It works for the record 2 but not for the record 3.
Thanks for any help. Don't hesitate to question me if not clear enough. ;)
EDIT:
Just one more thing: it's also possible that my_list contains more IDs than necessary. For exemple, with [2, 5, 6, 7] I should retrieve records 2 and 3.
Just remove the filter by count:
queryset = A.objects.prefetch_related('list_of_b')
for id in my_list:
queryset = queryset.filter(list_of_b=id)