






from __future__ import annotations

def      lowerCAmelCase__	(    _a       :			str  ,      _a       :			list[str] | None = None  ,      _a       :			dict[str, float] | None = None  ,      _a       :			bool = False  ,      ):
		snake_case_				:							Tuple						 =       cipher_alphabet or [chr(_a    ) for i in range(97  ,      1_23    )]

		# If the argument is None or the user provided an empty dictionary
		if not frequencies_dict:
				# Frequencies of letters in the english language (how much they show up)
				snake_case_				:							Dict						 =       {
				    "a": 0.08_497,
				    "b": 0.01_492,
				    "c": 0.02_202,
				    "d": 0.04_253,
				    "e": 0.11_162,
				    "f": 0.02_228,
				    "g": 0.02_015,
				    "h": 0.06_094,
				    "i": 0.07_546,
				    "j": 0.00_153,
				    "k": 0.01_292,
				    "l": 0.04_025,
				    "m": 0.02_406,
				    "n": 0.06_749,
				    "o": 0.07_507,
				    "p": 0.01_929,
				    "q": 0.00_095,
				    "r": 0.07_587,
				    "s": 0.06_327,
				    "t": 0.09_356,
				    "u": 0.02_758,
				    "v": 0.00_978,
				    "w": 0.02_560,
				    "x": 0.00_150,
				    "y": 0.01_994,
				    "z": 0.00_077,
				}
		else:
				# Custom frequencies dictionary
				snake_case_				:							Dict						 =       frequencies_dict

		if not case_sensitive:
				snake_case_				:							str						 =       ciphertext.lower()

		# Chi squared statistic values
		snake_case_				:							dict[int, tuple[float, str]]						 =       {}

		# cycle through all of the shifts
		for shift in range(len(_a    )    ):
				snake_case_				:							str						 =       ""

				# decrypt the message with the shift
				for letter in ciphertext:
						try:
								# Try to index the letter in the alphabet
								snake_case_				:							List[str]						 =       (alphabet_letters.index(letter.lower()    ) - shift) % len(
								    _a    )
								decrypted_with_shift += (
								    alphabet_letters[new_key].upper()
								    if case_sensitive and letter.isupper()
								    else alphabet_letters[new_key]
								)
						except ValueError:
								# Append the character if it isn't in the alphabet
								decrypted_with_shift += letter

				snake_case_				:							Union[str, Any]						 =       0.0

				# Loop through each letter in the decoded message with the shift
				for letter in decrypted_with_shift:
						if case_sensitive:
								snake_case_				:							int						 =       letter.lower()
								if letter in frequencies:
										# Get the amount of times the letter occurs in the message
										snake_case_				:							List[str]						 =       decrypted_with_shift.lower().count(_a    )

										# Get the excepcted amount of times the letter should appear based
										# on letter frequencies
										snake_case_				:							Tuple						 =       frequencies[letter] * occurrences

										# Complete the chi squared statistic formula
										snake_case_				:							Any						 =       ((occurrences - expected) ** 2) / expected

										# Add the margin of error to the total chi squared statistic
										chi_squared_statistic += chi_letter_value
						else:
								if letter.lower() in frequencies:
										# Get the amount of times the letter occurs in the message
										snake_case_				:							Optional[Any]						 =       decrypted_with_shift.count(_a    )

										# Get the excepcted amount of times the letter should appear based
										# on letter frequencies
										snake_case_				:							int						 =       frequencies[letter] * occurrences

										# Complete the chi squared statistic formula
										snake_case_				:							Any						 =       ((occurrences - expected) ** 2) / expected

										# Add the margin of error to the total chi squared statistic
										chi_squared_statistic += chi_letter_value

        # Add the data to the chi_squared_statistic_values dictionary
				snake_case_				:							Optional[int]						 =       (
				    chi_squared_statistic,
				    decrypted_with_shift,
				)

		# Get the most likely cipher by finding the cipher with the smallest chi squared
		# statistic
		def chi_squared_statistic_values_sorting_key(_a       :			int    ) -> tuple[float, str]:
				return chi_squared_statistic_values[key]

		snake_case_				:							int						 =       min(
		    _a  ,      key=_a  ,      )

		# Get all the data from the most likely cipher (key, decoded message)
		(
		    (
		    snake_case_
		) ,       (
		    snake_case_
		) ,       
		)				:							Dict						 =       chi_squared_statistic_values[most_likely_cipher]

		# Return the data on the most likely shift
		return (
		    most_likely_cipher,
		    most_likely_cipher_chi_squared_value,
		    decoded_most_likely_cipher,
		)








from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
lowercase  :							Optional[Any]			  =    2_00
# 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.
lowercase  :							Optional[Any]			  =    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.
lowercase  :							Union[str, Any]			  =    0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 10_00))

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

def      lowerCAmelCase__	(    _a       :			str  ,      _a       :			str    ):
		snake_case_				:							Tuple						 =       random.randint(0  ,      len(_a    ) - 1    )
		snake_case_				:							Any						 =       parent_a[:random_slice] + parent_a[random_slice:]
		snake_case_				:							Optional[Any]						 =       parent_a[:random_slice] + parent_a[random_slice:]
		return (child_a, child_a)

def      lowerCAmelCase__	(    _a       :			str  ,      _a       :			list[str]    ):
		snake_case_				:							str						 =       list(_a    )
		if random.uniform(0  ,      1    ) < MUTATION_PROBABILITY:
				snake_case_				:							Optional[Any]						 =       random.choice(_a    )
		return "".join(_a    )

def      lowerCAmelCase__	(    _a       :			tuple[str, float]  ,      _a       :			list[tuple[str, float]]  ,      _a       :			list[str]  ,      ):
		snake_case_				:							Tuple						 =       []
		# Generate more children proportionally to the fitness score.
		snake_case_				:							Optional[int]						 =       int(parent_a[1] * 1_00    ) + 1
		snake_case_				:							Tuple						 =       10 if child_n >= 10 else child_n
		for _ in range(_a    ):
				snake_case_				:							int						 =       population_score[random.randint(0  ,      _a    )][0]

				snake_case_ ,       snake_case_				:							Any						 =       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       :			str  ,      _a       :			list[str]  ,      _a       :			bool = True    ):

		# Verify if N_POPULATION is bigger than N_SELECTED
		if N_POPULATION < N_SELECTED:
				snake_case_				:							Any						 =       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.
		snake_case_				:							Optional[Any]						 =       sorted({c for c in target if c not in genes}    )
		if not_in_genes_list:
				snake_case_				:							str						 =       F'''{not_in_genes_list} is not in genes list, evolution cannot converge'''
				raise ValueError(_a    )

		# Generate random starting population.
		snake_case_				:							Optional[int]						 =       []
		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.
		snake_case_ ,       snake_case_				:							Dict						 =       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.
				snake_case_				:							Optional[int]						 =       [evaluate(_a  ,      _a    ) for item in population]

				# Check if there is a matching evolution.
				snake_case_				:							Any						 =       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.
				snake_case_				:							Union[str, Any]						 =       population[: int(N_POPULATION / 3    )]
				population.clear()
				population.extend(_a    )
				# Normalize population score to be between 0 and 1.
				snake_case_				:							int						 =       [
				    (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__":
							lowercase  :							Dict			  =    (
							    '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!'''
							)
							lowercase  :							Optional[int]			  =    list(
							    ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm'''
							    '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\'''
							)
							lowercase  ,lowercase  ,lowercase  :							Optional[Any]			  =    basic(target_str, genes_list)
							print(
							    F"""\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}"""
							)
