from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
lowerCamelCase__  =					200
# Number of elements selected in every generation of evolution. The selection takes
# place from best to worst of that generation and must be smaller than N_POPULATION.
lowerCamelCase__  =					50
# Probability that an element of a generation can mutate, changing one of its genes.
# This will guarantee that all genes will be used during evolution.
lowerCamelCase__  =					0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))


def 				lowerCAmelCase__       (			a__    ,     a__ )      ->tuple[str, float]:




  '''simple docstring'''

  _UpperCamelCase           =    len([g for position, g in enumerate(a__ ) if g == main_target[position]] )
  return (item, float(a__ ))


def 				lowerCAmelCase__       (			a__    ,     a__ )      ->tuple[str, str]:




  '''simple docstring'''

  _UpperCamelCase           =    random.randint(0    ,     len(a__ ) - 1 )
  _UpperCamelCase           =    parent_a[:random_slice] + parent_a[random_slice:]
  _UpperCamelCase           =    parent_a[:random_slice] + parent_a[random_slice:]
  return (child_a, child_a)


def 				lowerCAmelCase__       (			a__    ,     a__ )      ->str:




  '''simple docstring'''

  _UpperCamelCase           =    list(a__ )
  if random.uniform(0    ,     1 ) < MUTATION_PROBABILITY:
    _UpperCamelCase           =    random.choice(a__ )
  return "".join(a__ )


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__    ,     )      ->list[str]:




  '''simple docstring'''

  _UpperCamelCase           =    []
  # Generate more children proportionally to the fitness score.
  _UpperCamelCase           =    int(parent_a[1] * 100 ) + 1
  _UpperCamelCase           =    10 if child_n >= 10 else child_n
  for _ in range(a__ ):
    _UpperCamelCase           =    population_score[random.randint(0    ,     a__ )][0]

    _UpperCamelCase      ,						_UpperCamelCase           =    crossover(parent_a[0]    ,     a__ )
    # Append new string to the population list.
    pop.append(mutate(a__    ,     a__ ) )
    pop.append(mutate(a__    ,     a__ ) )
  return pop


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__ = True )      ->tuple[int, int, str]:




  '''simple docstring'''

  if N_POPULATION < N_SELECTED:
    _UpperCamelCase           =    f'{N_POPULATION} must be bigger than {N_SELECTED}'
    raise ValueError(a__ )
  # Verify that the target contains no genes besides the ones inside genes variable.
  _UpperCamelCase           =    sorted({c for c in target if c not in genes} )
  if not_in_genes_list:
    _UpperCamelCase           =    f'{not_in_genes_list} is not in genes list, evolution cannot converge'
    raise ValueError(a__ )

  # Generate random starting population.
  _UpperCamelCase           =    []
  for _ in range(a__ ):
    population.append("".join([random.choice(a__ ) for i in range(len(a__ ) )] ) )

  # Just some logs to know what the algorithms is doing.
  _UpperCamelCase      ,						_UpperCamelCase           =    0, 0

  # This loop will end when we find a perfect match for our target.
  while True:
    generation += 1
    total_population += len(a__ )

    # Random population created. Now it's time to evaluate.

    # Adding a bit of concurrency can make everything faster,
    #
    # import concurrent.futures
    # population_score: list[tuple[str, float]] = []
    # with concurrent.futures.ThreadPoolExecutor(
    #                                   max_workers=NUM_WORKERS) as executor:
    #     futures = {executor.submit(evaluate, item) for item in population}
    #     concurrent.futures.wait(futures)
    #     population_score = [item.result() for item in futures]
    #
    # but with a simple algorithm like this, it will probably be slower.
    # We just need to call evaluate for every item inside the population.
    _UpperCamelCase           =    [evaluate(a__    ,     a__ ) for item in population]

    # Check if there is a matching evolution.
    _UpperCamelCase           =    sorted(a__    ,     key=lambda a__ : x[1]    ,     reverse=a__ )
    if population_score[0][0] == target:
      return (generation, total_population, population_score[0][0])

    # Print the best result every 10 generation.
    # Just to know that the algorithm is working.
    if debug and generation % 10 == 0:
      print(
          f'\nGeneration: {generation}'
          f'\nTotal Population:{total_population}'
          f'\nBest score: {population_score[0][1]}'
          f'\nBest string: {population_score[0][0]}' )

    # Flush the old population, keeping some of the best evolutions.
    # Keeping this avoid regression of evolution.
    _UpperCamelCase           =    population[: int(N_POPULATION / 3 )]
    population.clear()
    population.extend(a__ )
    # Normalize population score to be between 0 and 1.
    _UpperCamelCase           =    [
        (item, score / len(a__ )) for item, score in population_score
    ]

    # This is selection
    for i in range(a__ ):
      population.extend(select(population_score[int(a__ )]    ,     a__    ,     a__ ) )
      # Check if the population has already reached the maximum value and if so,
      # break the cycle.  If this check is disabled, the algorithm will take
      # forever to compute large strings, but will also calculate small strings in
      # a far fewer generations.
      if len(a__ ) > N_POPULATION:
        break


if __name__ == "__main__":
   lowerCamelCase__  =					(
       '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!'''
   )
   lowerCamelCase__  =					list(
       ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm'''
       '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\'''
   )
   lowerCamelCase__,lowerCamelCase__,lowerCamelCase__  =					basic(target_str, genes_list)
   print(
       F"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}"
   )





# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__    ,     a__ )      ->str:




  '''simple docstring'''

  _UpperCamelCase           =    multiprocessing.Manager()
  _UpperCamelCase           =    manager.list()

  _UpperCamelCase           =    multiprocessing.Process(target=a__    ,     args=(check_program, result, timeout) )
  p.start()
  p.join(timeout=timeout + 1 )
  if p.is_alive():
    p.kill()

  if not result:
    result.append("timed out" )

  return {
      "task_id": task_id,
      "passed": result[0] == "passed",
      "result": result[0],
      "completion_id": completion_id,
  }


def 				lowerCAmelCase__       (			a__    ,     a__    ,     a__ )      ->Union[str, Any]:




  '''simple docstring'''

  with create_tempdir():
    # These system calls are needed when cleaning up tempdir.
    import os
    import shutil

    _UpperCamelCase           =    shutil.rmtree
    _UpperCamelCase           =    os.rmdir
    _UpperCamelCase           =    os.chdir

    # Disable functionalities that can make destructive changes to the test.
    reliability_guard()

    # Run program.
    try:
      _UpperCamelCase           =    {}
      with swallow_io():
        with time_limit(a__ ):
          exec(a__    ,     a__ )
      result.append("passed" )
    except TimeoutException:
      result.append("timed out" )
    except BaseException as e:
      result.append(f'failed: {e}' )

    # Needed for cleaning up.
    _UpperCamelCase           =    rmtree
    _UpperCamelCase           =    rmdir
    _UpperCamelCase           =    chdir


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->Optional[Any]:




  '''simple docstring'''

  def signal_handler(a__    ,     a__ ):
    raise TimeoutException("Timed out!" )

  signal.setitimer(signal.ITIMER_REAL    ,     a__ )
  signal.signal(signal.SIGALRM    ,     a__ )
  try:
    yield
  finally:
    signal.setitimer(signal.ITIMER_REAL    ,     0 )


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  _UpperCamelCase           =    WriteOnlyStringIO()
  with contextlib.redirect_stdout(a__ ):
    with contextlib.redirect_stderr(a__ ):
      with redirect_stdin(a__ ):
        yield


@contextlib.contextmanager
def 				lowerCAmelCase__       (			)      ->Optional[int]:




  '''simple docstring'''

  with tempfile.TemporaryDirectory() as dirname:
    with chdir(a__ ):
      yield dirname




class 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




 pass




class 					_UpperCAmelCase			(     io.StringIO  ):



 '''simple docstring'''




 def 		__UpperCAmelCase				(		self				:   List[str]							, *lowercase_				:   str							, **lowercase_				:   List[str])						->	Optional[Any]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   Any							, *lowercase_				:   List[Any]							, **lowercase_				:   Optional[int])						->	Optional[int]:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   int							, *lowercase_				:   int							, **lowercase_				:   str)						->	int:


   """simple docstring"""







   raise OSError







 def 		__UpperCAmelCase				(		self				:   List[Any]							, *lowercase_				:   Tuple							, **lowercase_				:   Tuple)						->	Tuple:


   """simple docstring"""







   return False




class 					_UpperCAmelCase			(     contextlib._RedirectStream  ):  # type: ignore



 '''simple docstring'''




 __A			       =					'''stdin'''


@contextlib.contextmanager
def 				lowerCAmelCase__       (			a__ )      ->str:




  '''simple docstring'''

  if root == ".":
    yield
    return
  _UpperCamelCase           =    os.getcwd()
  os.chdir(a__ )
  try:
    yield
  except BaseException as exc:
    raise exc
  finally:
    os.chdir(a__ )







def 				lowerCAmelCase__       (			a__=None )      ->Optional[int]:




  '''simple docstring'''

  if maximum_memory_bytes is not None:
    import resource

    resource.setrlimit(resource.RLIMIT_AS    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    resource.setrlimit(resource.RLIMIT_DATA    ,     (maximum_memory_bytes, maximum_memory_bytes) )
    if not platform.uname().system == "Darwin":
      resource.setrlimit(resource.RLIMIT_STACK    ,     (maximum_memory_bytes, maximum_memory_bytes) )

  faulthandler.disable()

  import builtins

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import os

  _UpperCamelCase           =    "1"

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import shutil

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None

  import subprocess

  _UpperCamelCase           =    None  # type: ignore

  _UpperCamelCase           =    None

  import sys

  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None
  _UpperCamelCase           =    None




