423,851 Members | 2,771 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,851 IT Pros & Developers. It's quick & easy.

cyclic crossover in genetic algorithm (python implementation)

P: 1
I have a python3 program that gives cycles for a given permutation. I want to know how to find a children out of it.

This is what I have to create a cycles;
Expand|Select|Wrap|Line Numbers
  1. def to_cycles(perm):
  2.     pi = {i+1: perm[i] for i in range(len(perm))}
  3.     cycles = []
  4.  
  5.     while pi:
  6.         elem0 = next(iter(pi)) # arbitrary starting element
  7.         this_elem = pi[elem0]
  8.         next_item = pi[this_elem]
  9.  
  10.         cycle = []
  11.         while True:
  12.             cycle.append(this_elem)
  13.             del pi[this_elem]
  14.             this_elem = next_item
  15.             if next_item in pi:
  16.                 next_item = pi[next_item]
  17.             else:
  18.                 break
  19.  
  20.         cycles.append(cycle)
  21.  
  22.     return cycles
  23. aa = to_cycles([4,1,6,2,3,5,8,9,7,10])
  24. print("array: ", aa)
  25. dicts = {}
  26. keys = range(0, len(aa)-1)
  27. for i in keys:
  28.         dicts[i] = aa[i]
  29. print(dicts)
Thanks for your input.
Oct 20 '18 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.