python list comprehension for loop

Let’s make a ‘python list & dictionary comprehension for loop’ example. It selects equal or greater than average value, then returns max 50 elements from dictionary.


def pick_biggest_elements(my_dict):
values = [x for x in my_dict.values()]
values.sort()
average = sum(values) / float(len(values))
upper_side = [el for el in values if el >= average]
temp = [key for key, value in my_dict.items() if value in upper_side]
if len(temp) > 50:
temp = temp[-50:]
return [eval(a) for a in temp]
Advertisements

python roulette wheel selection

Selection operator picks out individuals in the population for reproduction in genetic algorithms. Roulette wheel selection that an imaginary proportion of the wheel is assigned to each of the chromosomes based on their fitness value. The fitter chromosome has more chance to select than worse one. Roulette wheel selection is a kind of elitist selection that retaining the best individuals in a generation unchanged in the next generation.

Here an example of roulette wheel selection via pyhton. Imagine that you have population like


population = [[0,0,1,0,0,0,1],[0,1,0,0,0,0,0]]

And you use a proper fitness function regarding to your problem, and get a python dictionary to wrap your individuals and their fitness values like


population_fitness_dictionary = {"0,0,1,0,0,0,1": 1.245, "0,1,0,0,0,0,0":1.658}

Firstly, we can create a probability list (imaginary proportion of the wheel)


def get_probability_list():
fitness = population_fitness_dictionary.values()
total_fit = float(sum(fitness))
relative_fitness = [f/total_fit for f in fitness]
probabilities = [sum(relative_fitness[:i+1])
for i in range(len(relative_fitness))]
return probabilities

After that, we can write the roulette wheel selection function. Parameters of the function are our population, probability list of the population and a number to select desired individuals for reproduction.


def roulette_wheel_pop(population, probabilities, number):
chosen = []
for n in xrange(number):
r = random.random()
for (i, individual) in enumerate(population):
if r <= probabilities[i]:
chosen.append(list(individual))
break
return chosen

python comprehension split list

I have recently finished a master thesis about genetic algorithms for text segmentation via python, so I have a complicated relationship with python. Actually it always helps to me. This post consists of some python especially list and dictionary comprehensions.

First of all, splitting a list regarding with given another list. For example, you have a list which has sentences as elements. Another list is reference splitter and consists of 0s and 1s.


sentences = ["first sentence", "second sentence", "third sentence",
"fourth sentence", "fifth sentence"]

reference = [0,0,1,0]

This list indicates that cut the number of index of ‘1’ at the gap in the sentences list and result list will include two sublists


result = [["first sentence", "second sentence", "third sentence"],
["fourth sentence", "fifth sentence"]]


def split_segments_according_to_reference(reference, sentences):
temp = []
result = []
for i, j in zip(reference,range(len(sentences))):
temp.append(sentences[j])
if i == 1:
result.append(temp)
temp = []
if len(sentences) == len(reference)+1:
temp.append(sentences[-1])
result.append(temp)
temp = []
return result