import random

def find_imports(code):
    '''Extract import statements from code'''
    import ast
    try:
        tree = ast.parse(code)
        imports = []
        for n in ast.walk(tree):
            if isinstance(n, ast.Import):
                imports.extend(a.name for a in n.names)
            elif isinstance(n, ast.ImportFrom):
                imports.append(n.module)
        return imports
    except:
        return []

class GeneticAlgorithm:
    def __init__(self, target_length=20, mutation_rate=0.01, elite_count=2, 
                 tournament_size=3, max_generations=50, parents_per_couple=2):
        self.target_length = target_length
        self.mutation_rate = mutation_rate
        self.elite_count = elite_count
        self.tournament_size = tournament_size
        self.max_generations = max_generations
        self.parents_per_couple = parents_per_couple

    def generate_population(self, initial_pool):
        '''Initialize population with unique imports from top breeds'''
        population = []
        seen = set()
        
        for breed in random.sample(initial_pool, min(10, len(initial_pool))):
            imports = find_imports(breed)
            genes = sorted(list(set(imports)))  # Remove duplicates and sort
            gene_str = ','.join(genes)
            
            if gene_str not in seen:
                population.append({'genes': genes, 'fitness': len(genes)})
                seen.add(gene_str)
                
        return population

    def calculate_fitness(self, population):
        '''Fitness is number of unique libraries'''
        for individual in population:
            individual['fitness'] = len(individual['genes'])

    def select_parents(self, population):
        '''Tournament selection'''
        parents = []
        while len(parents) < self.elite_count + self.parents_per_couple * 2:
            tournament = random.sample(population, self.tournament_size)
            winner = max(tournament, key=lambda x: x['fitness'])
            parents.append(winner)
        return parents

    def crossover(self, parent1, parent2):
        '''Multi-parent genetic crossover'''
        genes_set1 = set(parent1['genes'])
        genes_set2 = set(parent2['genes'])
        
        # Create offspring by combining genes from multiple parents
        child_genes = genes_set1.union(genes_set2)
        return {'genes': list(child_genes), 'fitness': len(child_genes)}

    def mutate(self, individual):
        '''Mutation rate based on adding or removing libraries'''
        mutations = ['add', 'remove']
        
        if random.random() < self.mutation_rate:
            # Try adding a new library
            new_lib = input("Suggest a library to add: ")
            if new_lib not in individual['genes']:
                individual['genes'].append(new_lib)
                individual['fitness'] += 1
                
        if random.random() < self.mutation_rate and len(individual['genes']) > 3:
            # Try removing an existing library
            to_remove = random.choice(individual['genes'])
            individual['genes'].remove(to_remove)
            individual['fitness'] -= 1

    def evolve(self, initial_pool):
        population = self.generate_population(initial_pool)
        
        for generation in range(self.max_generations):
            self.calculate_fitness(population)
            
            parents = self.select_parents(population)
            new_population = []
            
            # Elitism: keep best individuals
            for parent in sorted(parents, key=lambda x: -x['fitness'])[:self.elite_count]:
                new_population.append({'genes': parent['genes'].copy(), 
                                      'fitness': parent['fitness']})
                
            # Genetic crossover and mutation
            random_parents = random.sample(parents[self.elite_count:], 
                                          len(parents) - self.elite_count)
            
            for i in range(0, len(random_parents), 2):
                if i + 1 < len(random_parents):
                    child1 = self.crossover(random_parents[i], random_parents[i+1])
                    self.mutate(child1)
                    new_population.append(child1)
                    
                    child2 = self.crossover(random_parents[i], random_parents[i+1])
                    self.mutate(child2)
                    new_population.append(child2)
                    
            population = new_population
        
        # Select the best individual
        winner = max(population, key=lambda x: x['fitness'])
        return winner['genes']

# Example usage:
genetic_engine = GeneticAlgorithm()
top_breeds = [
    "import numpy as np\nimport pandas as pd",
    "from sklearn.model_selection import train_test_split\nimport tensorflow as tf",
    "import torch\nfrom torchvision import datasets, transforms"
]
optimized_imports = genetic_engine.evolve(top_breeds)
print("Optimized imports: ", optimized_imports)
def solve_equation(a, b, c):
    '''Solve ax + b = c, return x'''
    if a == 0:
        return None if b != c else 0
    return (c - b) / a
def logic_and(*args):
    '''Logical AND of all arguments'''
    return all(args)
def logic_or(*args):
    '''Logical OR of all arguments'''
    return any(args)
def find_imports(code):
    '''Extract import statements from code'''
    import ast
    try:
        tree = ast.parse(code)
        imports = []
        for n in ast.walk(tree):
            if isinstance(n, ast.Import):
                imports.extend(a.name for a in n.names)
            elif isinstance(n, ast.ImportFrom):
                imports.append(n.module)
        return imports
    except:
        return []
def detect_security_issue(code):
    '''Detect dangerous patterns in code'''
    dangers = ['eval(', 'exec(', 'os.system(', '__import__', 'subprocess.call(']
    found = [d for d in dangers if d in code]
    return found
def deep_copy(obj):
    '''Deep copy any object'''
    import copy
    return copy.deepcopy(obj)
def merge_dicts(d1, d2):
    '''Merge two dictionaries'''
    result = d1.copy()
    result.update(d2)
    return result
def unique_elements(lst):
    '''Return unique elements preserving order'''
    seen = set()
    return [x for x in lst if not (x in seen or seen.add(x))]
def measure_complexity(code):
    '''Estimate code complexity (lines, nesting)'''
    lines = len([l for l in code.split('\n') if l.strip()])
    nesting = max(len(l) - len(l.lstrip()) for l in code.split('\n') if l.strip()) // 4
    return {"lines": lines, "max_nesting": nesting}
def generate_test(func_name, inputs, expected):
    '''Generate a test case string'''
    return f"assert {func_name}({inputs}) == {expected}" 
def split_task(task, n=3):
    '''Split a task into n subtasks (simple version)'''
    words = task.split()
    chunk_size = max(1, len(words) // n)
    return [' '.join(words[i:i+chunk_size]) for i in range(0, len(words), chunk_size)][:n]
def create_memory():
    '''Create a simple key-value memory store'''
    return {}

def store(memory, key, value):
    memory[key] = value
    return memory

def retrieve(memory, key):
    return memory.get(key)
def tokenize(text):
    '''Split text into tokens'''
    import re
    return re.findall(r'\b\w+\b', text.lower())
def extract_numbers(text):
    '''Extract all numbers from text'''
    import re
    return [int(n) for n in re.findall(r'\d+', text)]
def count_functions(code):
    import ast
    try:
        tree = ast.parse(code)
        return len([n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)])
    except:
        return -1
def count_classes(code):
    import ast
    try:
        tree = ast.parse(code)
        return len([n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)])
    except:
        return -1
