Advertisement
askanton

Відтворюємо еволюцію на #python | Вчимо щурів змінювати колір хутра залежно від сезону

Apr 15th, 2023
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. from flask import Flask, render_template, request
  2. import random
  3. #Відтворюемо еволюцію на python | Вчимо щурів змінювати колір хутра залежно від сезону
  4. app = Flask(__name__)
  5. sindex = 0
  6. # Популяція
  7. population = ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']
  8.  
  9.  
  10. # Репродуктивна функція
  11. def reproduction(parents):
  12.     children = []
  13.     for i in range(len(parents)):
  14.         child = ''
  15.         for j in range(len(parents[i])):
  16.             if random.random() < 0.5:
  17.                 child += parents[i][j]
  18.             else:
  19.                 child += parents[random.randint(0, len(parents) - 1)][j]
  20.         children.append(child)
  21.     return children
  22.  
  23.  
  24. # Мутації
  25. def mutation(individual, environment):
  26.     for i in range(len(individual)):
  27.         if environment == 'Трава':
  28.             season_mutation = random.choices(["A", "B"], weights=(80, 20), k=1)
  29.         else:
  30.             season_mutation = random.choices(["A", "B"], weights=(20, 80), k=1)
  31.     return season_mutation
  32.  
  33.  
  34. # Еволюційний процес
  35. def evolve(population, environment):
  36.     children = reproduction(population)
  37.     population = [mutation(child, environment) for child in children]
  38.     return population
  39.  
  40.  
  41. # Зміна середовища
  42. def change_environment(environment):
  43.     global sindex
  44.     sindex += 1
  45.     #env_types = ['Сніг', 'Трава']
  46.     #if environment == 'Сніг':
  47.         #result = random.choices(env_types, weights=(60, 40), k=1)
  48.     #else:
  49.         #result = random.choices(env_types, weights=(40, 60), k=1)
  50.     #return result
  51.  
  52.     # 10 сезонів снігу
  53.     if sindex < 10:
  54.         return 'Сніг'
  55.     else:
  56.         return 'Трава'
  57.  
  58. @app.route('/', methods=['GET', 'POST'])
  59. def index():
  60.     global population, environment
  61.     render_template('index.html', population=population, environment=environment)
  62.     if request.method == 'POST':
  63.         environment = change_environment(environment)
  64.         population = evolve(population, environment)
  65.         #print(population)
  66.     return render_template('index.html', population=population, environment=environment)
  67.  
  68.  
  69. if __name__ == '__main__':
  70.     environment = 'Сніг'
  71.     app.run(debug=True)
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement