


from __future__ import annotations

import random

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


def 					lowerCamelCase__						(   a						: str						,	a						: str					)     ->						str:





			"""simple docstring"""
			a__			:str    	=     len([g for position, g in enumerate(_SCREAMING_SNAKE_CASE					) if g == main_target[position]]					)
			return (item, float(_SCREAMING_SNAKE_CASE					))


def 					lowerCamelCase__						(   a						: str						,	a						: str					)     ->						Union[str, Any]:





			"""simple docstring"""
			a__			:str    	=     random.randint(0						,	len(_SCREAMING_SNAKE_CASE					) - 1					)
			a__			:Union[str, Any]    	=     parent_a[:random_slice] + parent_a[random_slice:]
			a__			:List[str]    	=     parent_a[:random_slice] + parent_a[random_slice:]
			return (child_a, child_a)


def 					lowerCamelCase__						(   a						: str						,	a						: list[str]					)     ->						List[str]:





			"""simple docstring"""
			a__			:List[str]    	=     list(_SCREAMING_SNAKE_CASE					)
			if random.uniform(0						,	1					) < MUTATION_PROBABILITY:
						a__			:List[str]    	=     random.choice(_SCREAMING_SNAKE_CASE					)
			return "".join(_SCREAMING_SNAKE_CASE					)


def 					lowerCamelCase__						(   a						: tuple[str, float]						,	a						: list[tuple[str, float]]						,	a						: list[str]						,	)     ->						Optional[int]:





			"""simple docstring"""
			a__			:Dict    	=     []
			# Generate more children proportionally to the fitness score.
			a__			:str    	=     int(parent_a[1] * 100					) + 1
			a__			:Optional[Any]    	=     10 if child_n >= 10 else child_n
			for _ in range(_SCREAMING_SNAKE_CASE					):
						a__			:List[Any]    	=     population_score[random.randint(0						,	_SCREAMING_SNAKE_CASE					)][0]

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


def 					lowerCamelCase__						(   a						: str						,	a						: list[str]						,	a						: bool = True					)     ->						List[Any]:





			"""simple docstring"""

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

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

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

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

						# 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.
						a__			:Optional[Any]    	=     [evaluate(_SCREAMING_SNAKE_CASE						,	_SCREAMING_SNAKE_CASE					) for item in population]

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

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


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



import os
import random
import sys

from . import cryptomath_module as cryptoMath  # noqa: N812
from . import rabin_miller as rabinMiller  # noqa: N812






def     lowerCAmelCase_			(   ):
						print("""Making key files..."""			)
						make_key_files("""rsa"""		, 1024			)
						print("""Key files generation successful."""			)






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				int			):
						print("""Generating prime p..."""			)
						UpperCamelCase_		:							Tuple  =		rabinMiller.generate_large_prime(_SCREAMING_SNAKE_CASE			)
						print("""Generating prime q..."""			)
						UpperCamelCase_		:							List[Any]  =		rabinMiller.generate_large_prime(_SCREAMING_SNAKE_CASE			)
						UpperCamelCase_		:							List[str]  =		p * q

						print("""Generating e that is relatively prime to (p - 1) * (q - 1)..."""			)
						while True:
												UpperCamelCase_		:							Union[str, Any]  =		random.randrange(2 ** (key_size - 1)		, 2 ** (key_size)			)
												if cryptoMath.gcd(_SCREAMING_SNAKE_CASE		, (p - 1) * (q - 1)			) == 1:
																		break

						print("""Calculating d that is mod inverse of e..."""			)
						UpperCamelCase_		:							Tuple  =		cryptoMath.find_mod_inverse(_SCREAMING_SNAKE_CASE		, (p - 1) * (q - 1)			)

						UpperCamelCase_		:							Tuple  =		(n, e)
						UpperCamelCase_		:							int  =		(n, d)
						return (public_key, private_key)






def     lowerCAmelCase_			(   _SCREAMING_SNAKE_CASE     :				str		, _SCREAMING_SNAKE_CASE     :				int			):
						if os.path.exists(f'''{name}_pubkey.txt'''			) or os.path.exists(f'''{name}_privkey.txt'''			):
												print("""\nWARNING:"""			)
												print(
												    f'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'''
												    """Use a different name or delete these files and re-run this program."""			)
												sys.exit()

						UpperCamelCase_,UpperCamelCase_		:							str  =		generate_key(_SCREAMING_SNAKE_CASE			)
						print(f'''\nWriting public key to file {name}_pubkey.txt...'''			)
						with open(f'''{name}_pubkey.txt'''		, """w"""			) as out_file:
												out_file.write(f'''{key_size},{public_key[0]},{public_key[1]}'''			)

						print(f'''Writing private key to file {name}_privkey.txt...'''			)
						with open(f'''{name}_privkey.txt'''		, """w"""			) as out_file:
												out_file.write(f'''{key_size},{private_key[0]},{private_key[1]}'''			)


if __name__ == "__main__":
	main()






