Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,7 @@
* [Fuzzy Set Operations](fuzzy_logic/fuzzy_set_operations.py)

## [Genetic Algorithm](genetic_algorithm)
* [Basic Number](genetic_algorithm/basic_number.py)
* [Basic String](genetic_algorithm/basic_string.py)

## [Geodesy](geodesy)
Expand Down Expand Up @@ -876,6 +877,7 @@
* [Test Factorial](maths/test_factorial.py)
* [Test Prime Check](maths/test_prime_check.py)
* [Three Sum](maths/three_sum.py)
* [Tonelli Shanks](maths/tonelli_shanks.py)
* [Trailing Zeroes](maths/trailing_zeroes.py)
* [Trapezoidal Rule](maths/trapezoidal_rule.py)
* [Triplet Sum](maths/triplet_sum.py)
Expand Down
56 changes: 56 additions & 0 deletions genetic_algorithm/basic_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import doctest
import random


def fitness_function(input_value: float) -> float:
"""
Calculate the fitness (objective) function value for a given input.

Args:
input_value (float): The input value for which the fitness is calculated.

Returns:
float: The fitness value calculated for the input.

Raises:
ValueError: If the input is not a valid floating-point number.

Example:
>>> fitness_function(2.5)
0.75
>>> fitness_function(-1.0)
6.0
"""
if not isinstance(input_value, (int, float)):
raise ValueError("Input must be a valid number.")

# Define your fitness function here (e.g., x^2, or any other function)
return input_value**2 - 3 * input_value + 2


def genetic_algorithm() -> tuple[float, float]:
"""
A simplified genetic algorithm example.

Example:
>>> random.seed(42)
>>> best_solution, best_fitness = genetic_algorithm()
>>> abs(best_solution - (-1.45)) < 0.1
False
>>> abs(best_fitness - 6.0) < 0.1 # Check if the best fitness is within a tolerance
False
"""
population = [random.uniform(-2, 2) for _ in range(100)]
best_solution = min(population, key=fitness_function)
best_fitness = fitness_function(best_solution)
return best_solution, best_fitness


if __name__ == "__main__":
# Example usage
input_value = float(input("Enter the value of input_value: ").strip())
fitness = fitness_function(input_value)
print(f"The fitness for input_value = {input_value} is {fitness}.")

# Run the doctests
doctest.testmod()