import json import logging from flask import request, jsonify from routes import app logger = logging.getLogger(__name__) @app.route('/digital-colony', methods=['POST']) def evaluate(): data = request.get_json() logging.info("Data received for evaluation: {}".format(data)) results = [] try: for item in data: generations = item['generations'] colony = list(map(int, item['colony'])) logging.info(f"Evaluating colony: {colony} for {generations} generations") weight = calculate_weight_after_generations(colony, generations) logging.info(f"Weight of colony: {weight}") results.append(str(weight)) logging.info("Results: {}".format(results)) return jsonify(results) except Exception as e: logging.error("Error occurred while processing data: {}".format(e)) return jsonify([]) logging.info("Results: {}".format(results)) return jsonify(results) def calculate_signature(d1, d2, signature_cache): pair = (d1, d2) if pair in signature_cache: return signature_cache[pair] if d1 > d2: signature = d1 - d2 elif d2 > d1: signature = 10 - (d2 - d1) else: signature = 0 signature_cache[pair] = signature return signature def generate_next_colony(colony, signature_cache): new_colony = [] weight = sum(colony) for i in range(len(colony) - 1): d1, d2 = colony[i], colony[i + 1] signature = calculate_signature(d1, d2, signature_cache) new_digit = (weight + signature) % 10 new_colony.append(d1) new_colony.append(new_digit) new_colony.append(colony[-1]) return new_colony def calculate_weight_after_generations(initial_colony, generations): colony = [int(d) for d in initial_colony] signature_cache = {} for _ in range(generations): colony = generate_next_colony(colony, signature_cache) # print(colony, sum(colony)) # print("") return sum(colony)