



"""simple docstring"""





from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
__lowerCAmelCase       :					Any      					=					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       :					Tuple      					=					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       :					Tuple      					=					0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Any					, __UpperCamelCase      :			Dict    ):


						'''simple docstring'''






						snake_case_   : str						=			len([g for position, g in enumerate(lowercase_    ) if g == main_target[position]]    )
						return (item, float(lowercase_    ))
def 	__lowerCAmelCase						(		__UpperCamelCase      :			str					, __UpperCamelCase      :			Union[str, Any]    ):


						'''simple docstring'''






						snake_case_   : Tuple						=			random.randint(0					, len(lowercase_    ) - 1    )
						snake_case_   : Dict						=			parent_a[:random_slice] + parent_a[random_slice:]
						snake_case_   : Tuple						=			parent_a[:random_slice] + parent_a[random_slice:]
						return (child_a, child_a)
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Tuple					, __UpperCamelCase      :			Optional[int]    ):


						'''simple docstring'''






						snake_case_   : int						=			list(lowercase_    )
						if random.uniform(0					, 1    ) < MUTATION_PROBABILITY:
												snake_case_   : int						=			random.choice(lowercase_    )
						return "".join(lowercase_    )
def 	__lowerCAmelCase						(		__UpperCamelCase      :			List[Any]					, __UpperCamelCase      :			Tuple					, __UpperCamelCase      :			List[str]					, ):


						'''simple docstring'''






						snake_case_   : Optional[Any]						=			[]
						# Generate more children proportionally to the fitness score.
						snake_case_   : List[str]						=			int(parent_a[1] * 1_0_0    ) + 1
						snake_case_   : Union[str, Any]						=			1_0 if child_n >= 1_0 else child_n
						for _ in range(lowercase_    ):
												snake_case_   : Dict						=			population_score[random.randint(0					, lowercase_    )][0]

												snake_case_   : Dict						=			crossover(parent_a[0]					, lowercase_    )
												# Append new string to the population list.
												pop.append(mutate(lowercase_					, lowercase_    )    )
												pop.append(mutate(lowercase_					, lowercase_    )    )
						return pop
def 	__lowerCAmelCase						(		__UpperCamelCase      :			Union[str, Any]					, __UpperCamelCase      :			List[str]					, __UpperCamelCase      :			Optional[int] = True    ):


						'''simple docstring'''






						if N_POPULATION < N_SELECTED:
												snake_case_   : List[str]						=			F'{N_POPULATION} must be bigger than {N_SELECTED}'
												raise ValueError(lowercase_    )
						# Verify that the target contains no genes besides the ones inside genes variable.
						snake_case_   : int						=			sorted({c for c in target if c not in genes}    )
						if not_in_genes_list:
												snake_case_   : int						=			F'{not_in_genes_list} is not in genes list, evolution cannot converge'
												raise ValueError(lowercase_    )

						# Generate random starting population.
						snake_case_   : Union[str, Any]						=			[]
						for _ in range(lowercase_    ):
												population.append("""""".join([random.choice(lowercase_    ) for i in range(len(lowercase_    )    )]    )    )

						# Just some logs to know what the algorithms is doing.
						snake_case_   : str						=			0, 0

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

												# 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.
												snake_case_   : int						=			[evaluate(lowercase_					, lowercase_    ) for item in population]

												# Check if there is a matching evolution.
												snake_case_   : Optional[Any]						=			sorted(lowercase_					, key=lambda __UpperCamelCase    : x[1]					, reverse=lowercase_    )
												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 % 1_0 == 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.
												snake_case_   : str						=			population[: int(N_POPULATION / 3    )]
												population.clear()
												population.extend(lowercase_    )
												# Normalize population score to be between 0 and 1.
												snake_case_   : str						=			[
												    (item, score / len(lowercase_    )) for item, score in population_score
												]

												# This is selection
												for i in range(lowercase_    ):
																		population.extend(select(population_score[int(lowercase_    )]					, lowercase_					, lowercase_    )    )
																		# 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(lowercase_    ) > N_POPULATION:
																								break


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






"""simple docstring"""





def 	__lowerCAmelCase						(		__UpperCamelCase      :			int					, __UpperCamelCase      :			int    ):


						'''simple docstring'''






						snake_case_   : Any						=			1  # To kept the Calculated Value
						# Since C(n, k) = C(n, n-k)
						if k > (n - k):
												snake_case_   : Optional[int]						=			n - k
						# Calculate C(n,k)
						for i in range(__UpperCamelCase    ):
												result *= n - i
												result //= i + 1
						return result
def 	__lowerCAmelCase						(		__UpperCamelCase      :			int    ):


						'''simple docstring'''






						return binomial_coefficient(2 * node_count					, __UpperCamelCase    ) // (node_count + 1)
def 	__lowerCAmelCase						(		__UpperCamelCase      :			int    ):


						'''simple docstring'''






						if n < 0:
												raise ValueError("""factorial() not defined for negative values"""    )
						snake_case_   : Optional[int]						=			1
						for i in range(1					, n + 1    ):
												result *= i
						return result
def 	__lowerCAmelCase						(		__UpperCamelCase      :			int    ):


						'''simple docstring'''






						return catalan_number(__UpperCamelCase    ) * factorial(__UpperCamelCase    )


if __name__ == "__main__":
					__lowerCAmelCase       :					Optional[Any]      					=					int(input('''Enter the number of nodes: ''').strip() or 0)
					if node_count <= 0:
										raise ValueError('''We need some nodes to work with.''')
					print(
					    F'''Given {node_count} nodes, there are {binary_tree_count(node_count)} '''
					    F'''binary trees and {catalan_number(node_count)} binary search trees.'''
					)

