Advertisement
_eremec_

Untitled

Feb 22nd, 2017
447
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. import random
  2. import copy
  3. from string import ascii_lowercase
  4.  
  5.  
  6. def get_rand_pair(s_len, symbols):
  7.     return (random.randint(0, s_len-1), random.choice(symbols))
  8.  
  9. def get_N_most_successful_seqs(offsprings, s_flag, N):
  10.     match_pairs = sorted([(match_strs(string, s_flag), string)
  11.                         for string in offsprings])
  12.     return [el[1] for el in match_pairs[-N::]]
  13.  
  14. def match_strs(s, s_flag):
  15.     lenght = len(s)
  16.     count = 0
  17.     for i in range(lenght):
  18.         if s[i] == s_flag[i]:
  19.             count += 1
  20.     return count
  21.  
  22. def gen_new_str(s_list, symbols):
  23.     new_s = copy.copy(s_list)
  24.     pair = get_rand_pair(len(s_list), symbols)
  25.     new_s.pop(pair[0])
  26.     new_s.insert(pair[0], pair[1])
  27.     return new_s
  28.  
  29. def generate_first_gen(s_start, symbols):
  30.     return [gen_new_str(s_start, symbols) for _ in range(10)]
  31.  
  32. def generate_new_gen(symbols, offsprings, s_start):
  33.     new_gen = []
  34.     for string in offsprings:
  35.         for i in range(10):
  36.             new_gen.append(gen_new_str(string, symbols))
  37.     return get_N_most_successful_seqs(new_gen, s_flag, 10)
  38.  
  39. symbols = ascii_lowercase + ' '
  40. s_flag = list('what a lovely day')
  41. s_start = list('rtdafhdkv jfkslgf')
  42.  
  43. offsprings = generate_first_gen(s_start, symbols)
  44. count = 0
  45.  
  46. while  True:
  47.     offsprings = generate_new_gen(symbols, offsprings, 10)
  48.     count += 1
  49.     if s_flag in offsprings:
  50.         print(offsprings)
  51.         print(count)
  52.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement