Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask, render_template, request
- import random
- #Відтворюемо еволюцію на python | Вчимо щурів змінювати колір хутра залежно від сезону
- app = Flask(__name__)
- sindex = 0
- # Популяція
- population = ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']
- # Репродуктивна функція
- def reproduction(parents):
- children = []
- for i in range(len(parents)):
- child = ''
- for j in range(len(parents[i])):
- if random.random() < 0.5:
- child += parents[i][j]
- else:
- child += parents[random.randint(0, len(parents) - 1)][j]
- children.append(child)
- return children
- # Мутації
- def mutation(individual, environment):
- for i in range(len(individual)):
- if environment == 'Трава':
- season_mutation = random.choices(["A", "B"], weights=(80, 20), k=1)
- else:
- season_mutation = random.choices(["A", "B"], weights=(20, 80), k=1)
- return season_mutation
- # Еволюційний процес
- def evolve(population, environment):
- children = reproduction(population)
- population = [mutation(child, environment) for child in children]
- return population
- # Зміна середовища
- def change_environment(environment):
- global sindex
- sindex += 1
- #env_types = ['Сніг', 'Трава']
- #if environment == 'Сніг':
- #result = random.choices(env_types, weights=(60, 40), k=1)
- #else:
- #result = random.choices(env_types, weights=(40, 60), k=1)
- #return result
- # 10 сезонів снігу
- if sindex < 10:
- return 'Сніг'
- else:
- return 'Трава'
- @app.route('/', methods=['GET', 'POST'])
- def index():
- global population, environment
- render_template('index.html', population=population, environment=environment)
- if request.method == 'POST':
- environment = change_environment(environment)
- population = evolve(population, environment)
- #print(population)
- return render_template('index.html', population=population, environment=environment)
- if __name__ == '__main__':
- environment = 'Сніг'
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement