{"record":{"id":"aadd245b29336135","repo":"TheAlgorithms/Python","slug":"n-population-must-be-bigger-than-n-selected","errorCode":null,"errorMessage":"{N_POPULATION} must be bigger than {N_SELECTED}","messagePattern":"(.+?) must be bigger than (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"genetic_algorithm/basic_string.py","lineNumber":125,"sourceCode":"    Traceback (most recent call last):\n        ...\n    ValueError: ['e'] is not in genes list, evolution cannot converge\n    >>> genes.remove(\"s\")\n    >>> basic(\"test\", genes)\n    Traceback (most recent call last):\n        ...\n    ValueError: ['e', 's'] is not in genes list, evolution cannot converge\n    >>> genes.remove(\"t\")\n    >>> basic(\"test\", genes)\n    Traceback (most recent call last):\n        ...\n    ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge\n    \"\"\"\n\n    # Verify if N_POPULATION is bigger than N_SELECTED\n    if N_POPULATION < N_SELECTED:\n        msg = f\"{N_POPULATION} must be bigger than {N_SELECTED}\"\n        raise ValueError(msg)\n    # Verify that the target contains no genes besides the ones inside genes variable.\n    not_in_genes_list = sorted({c for c in target if c not in genes})\n    if not_in_genes_list:\n        msg = f\"{not_in_genes_list} is not in genes list, evolution cannot converge\"\n        raise ValueError(msg)\n\n    # Generate random starting population.\n    population = []\n    for _ in range(N_POPULATION):\n        population.append(\"\".join([random.choice(genes) for i in range(len(target))]))\n\n    # Just some logs to know what the algorithms is doing.\n    generation, total_population = 0, 0\n\n    # This loop will end when we find a perfect match for our target.\n    while True:\n        generation += 1\n        total_population += len(population)","sourceCodeStart":107,"sourceCodeEnd":143,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/genetic_algorithm/basic_string.py#L107-L143","documentation":"Raised by basic() in genetic_algorithm/basic_string.py when N_POPULATION < N_SELECTED. The selection step picks N_SELECTED parents from the population each generation; selecting more individuals than exist would either crash the random sampler or destroy the gene pool, so the function validates this precondition first.","triggerScenarios":"Calling basic('test', genes, N_POPULATION=100, N_SELECTED=200) or via the module defaults (N_POPULATION=300, N_SELECTED=50 — safe) with custom values where selected exceeds population.","commonSituations":"Tuning GA hyperparameters and shrinking the population for speed while leaving selection pressure high, or swapping the two values when calling.","solutions":["Ensure N_POPULATION > N_SELECTED; a common healthy ratio is population 5-10x selected.","Re-read the defaults in the module (300 vs 50) before overriding only one of them.","Scale both together: if you shrink population to 50, drop selected to ~10."],"exampleFix":"# before\nbasic('test', ascii_letters, N_POPULATION=50, N_SELECTED=100)  # inverted\n\n# after\nbasic('test', ascii_letters, N_POPULATION=200, N_SELECTED=50)","handlingStrategy":"validation","validationCode":"if N_POPULATION <= N_SELECTED:\n    raise ValueError(\n        f'need N_POPULATION > N_SELECTED, got {N_POPULATION} <= {N_SELECTED}'\n    )\nbasic(target, genes, N_POPULATION, N_SELECTED)","typeGuard":null,"tryCatchPattern":"try:\n    basic('test', genes, pop, sel)\nexcept ValueError as exc:\n    if 'must be bigger' in str(exc):\n        sel = max(1, pop // 4)\n        basic('test', genes, pop, sel)\n    else:\n        raise","preventionTips":["Keep the population/selected ratio explicit in config comments.","Change hyperparameters in pairs, never population alone."],"tags":["genetic-algorithm","hyperparameters","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}