SlideShare a Scribd company logo
Introduction to
Genetic Algorithms
with Python
Hello World!
The number game
Reach back in your
memory to a game we
played as kids.
Pick a number
between 1 and 10.
(pick 3)
Is your number 2?
No
Is it 7?
No
Is it 3?
Yes
That works
reasonably well for
1..10 but...
it becomes boring as
we increase the range
to 1..100.
Why?
Because we have
no way to
improve our guesses.
The guess is either
right or wrong
so it becomes a
mechanical process.
Is it 1? No
Is it 2? No
Is it 3? No
Is it 4? No
So, to make it
more interesting
instead of no,
let's say
higher or lower.
(pick 3 again)
Is your number 1?
Higher
7?
Lower
3?
Correct
At this point, the
person who evolves
the most efficient
guessing strategy wins.
Domain knowledge
When playing this
game we make use of
domain knowledge.
For example,
after this sequence:
1? Higher
7? Lower
Why wouldn't we guess
8, 9, or 10?
Because we know
that those numbers
are not lower than 7.
Why wouldn't we guess
1?
Because we already
tried it.
We use our memory
of what we've tried,
our successes
and failures,
and our
knowledge of numbers
to make better guesses.
A genetic algorithm
does not know
what lower means.
It has no intelligence.
It does not learn.
It will make the same
mistakes every time.
It will only be as good
at solving a problem
as the person
who writes the code.
And yet, it can be used
to find solutions to
problems that
humans would
struggle to solve or
could not solve at all.
How is that possible?
Genetic algorithms use
random exploration
of the problem space
combined with
evolutionary processes
like mutation and
crossover - exchange
of genetic information -
to improve guesses.
But also, because they
have no experience in
the problem domain
they try things
a human would never
think to try.
Thus, a person using
a genetic algorithm
may learn more about
the problem space and
potential solutions.
This helps them to
improve the algorithm,
in a virtuous cycle.
What can we learn
from this?
Genetic algorithms
should make
informed guesses.
Guess the password
Let's see how
this applies to
guessing a password.
We'll start by randomly
generating an initial
sequence of letters
then mutate/change
one random letter
in that sequence
at a time until the
sequence of letters is
"Hello World!"
Psuedo code
_letters = [a..zA..Z !]
target = "Hello World!"
guess = get 12 random letters from _letters
while guess != target:
index = get random value from [0..length of target]
guess[index] = get 1 random value from _letters
If you try this in your
favorite programming
language...
you'll find that it
performs worse than
guessing numbers
using yes and no
because it cannot tell
when one guess is
better than another.
So, let's help it
make an
informed guess
by telling it how many
guessed letters are
in the correct spots.
For example
"World.Hello?"
would get 2
because only the 4th
letter of each word
is correct.
The number 2
indicates how close the
answer is to correct.
This is called
the fitness value.
"hello_world?"
would get
a fitness value of 9
because 9 letters are
correct. Only the
h, w, and ? are wrong.
First Program
Now we're ready to
write some Python.
Start with a
set of letters for genes
and a target password
Genes and target
geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!."
target = "Hello World!"
Note: You can run the code in your browser at
https://repl.it/CZL1/1
Generate a guess
Next we need a way to
generate a random
string of letters.
Generate parent
import random
…
def generate_parent(length):
genes = []
while len(genes) < length:
sampleSize = min(length - len(genes), len(geneSet))
genes.extend(random.sample(geneSet, sampleSize))
return ''.join(genes)
Fitness
The fitness value
the genetic algorithm
provides
is the only feedback
the engine gets
to guide it
toward a solution.
Our fitness value is
the total number
of correct letters.
Get fitness
def get_fitness(guess):
return sum(1 for expected, actual in zip(target, guess)
if expected == actual)
Mutation
We also need
a way to produce
a new guess
by mutating
the current guess.
We start by
converting the parent
string to an array.
Mutate
def mutate(parent):
childGenes = list(parent)
...
Then replace
1 letter in the array
with a randomly
selected one
Mutate (cont'd)
...
index = random.randint(0, len(parent) - 1)
newGene, alternate = random.sample(geneSet, 2)
childGenes[index] = alternate 
if newGene == childGenes[index] 
else newGene
...
and then
recombine the result
into a string.
Mutate (cont'd)
...
return ''.join(childGenes)
Display
Next, it is important
to monitor
what is happening
so that we can
stop the engine
if it gets stuck.
It also allows us to
learn what works
and what does not
so we can
improve the algorithm.
To do that we display a
visual representation
of the gene sequence,
which may not be
the literal
gene sequence,
its fitness value and
the total run time.
Display
import datetime
...
def display(guess):
timeDiff = datetime.datetime.now() - startTime
fitness = get_fitness(guess)
print("{0}t{1}t{2}".format(guess, fitness, str(timeDiff)))
Sample output
ftljCDPvhasn 1 0:00:00
Main
Now we're ready to
write the main
program.
We start with a
random guess.
Main
random.seed()
startTime = datetime.datetime.now()
bestParent = generate_parent(len(target))
bestFitness = get_fitness(bestParent)
display(bestParent)
...
Then we add
the heart of
the genetic engine.
It is a loop
that creates a guess,
Main loop
while True:
child = mutate(bestParent)
...
requests the fitness
for that guess
Main loop (cont'd)
...
childFitness = get_fitness(child)
...
then compares it to
the fitness of the
previous best guess
Main loop (cont'd)
…
if bestFitness >= childFitness:
continue
display(child)
if childFitness >= len(bestParent):
break
...
and keeps
the one with
the best fitness.
Main loop (cont't)
...
bestFitness, bestParent = childFitness, child
This cycle repeats
until a stop condition
occurs.
Here, we stop
when all the letters
match the target.
Run
Sample output
ftljCDPvhasn 1 0:00:00
ftljC Pvhasn 2 0:00:00
ftljC Pohasn 3 0:00:00.001000
HtljC Pohasn 4 0:00:00.002000
HtljC Wohasn 5 0:00:00.004000
Htljo Wohasn 6 0:00:00.005000
Htljo Wohas! 7 0:00:00.008000
Htljo Wohls! 8 0:00:00.010000
Heljo Wohls! 9 0:00:00.013000
Hello Wohls! 10 0:00:00.013000
Hello Wohld! 11 0:00:00.013000
Hello World! 12 0:00:00.015000
Congratulations!
You've written
a genetic algorithm
in Python!
Next step
The next step is to
extract the genetic
engine code
from that specific to
the password problem
so it can be reused.
Ready for more?
Continue the lesson on CodeProject
or learn about my book.
Ad

More Related Content

Similar to Introduction to Genetic Algorithms with Python - Hello World! (20)

Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.
Questpond
 
Introduction to Prime Numbers
Introduction to Prime NumbersIntroduction to Prime Numbers
Introduction to Prime Numbers
Luke Dunn
 
GCSE-Surds.pptx
GCSE-Surds.pptxGCSE-Surds.pptx
GCSE-Surds.pptx
BimboBbsax
 
data handling class 8
data handling class 8data handling class 8
data handling class 8
HimakshiKava
 
Multiplying Fractions
Multiplying FractionsMultiplying Fractions
Multiplying Fractions
Lynne Crowe
 
Computer Science Homework Help
Computer Science Homework HelpComputer Science Homework Help
Computer Science Homework Help
Programming Homework Help
 
Pseudorandom number generators powerpoint
Pseudorandom number generators powerpointPseudorandom number generators powerpoint
Pseudorandom number generators powerpoint
David Roodman
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Magic 8 ball putting it all together
Magic 8 ball  putting it all togetherMagic 8 ball  putting it all together
Magic 8 ball putting it all together
geekinlibrariansclothing
 
I have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdfI have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdf
FORTUNE2505
 
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHONmodule 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
FahmaFamzin
 
Math class 8 data handling
Math class 8 data handling Math class 8 data handling
Math class 8 data handling
HimakshiKava
 
MATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdf
MATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdfMATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdf
MATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdf
Jay Cris Miguel
 
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docxHierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
pooleavelina
 
Counting (Notes)
Counting (Notes)Counting (Notes)
Counting (Notes)
roshmat
 
Vpet sd-1.25.18
Vpet sd-1.25.18Vpet sd-1.25.18
Vpet sd-1.25.18
Thinkful
 
Python Math Concepts Book
Python Math Concepts BookPython Math Concepts Book
Python Math Concepts Book
Rohan Karunaratne
 
Applied 40S March 12, 2009
Applied 40S March 12, 2009Applied 40S March 12, 2009
Applied 40S March 12, 2009
Darren Kuropatwa
 
CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1
johnnygoodman
 
Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.Most asked JAVA Interview Questions & Answers.
Most asked JAVA Interview Questions & Answers.
Questpond
 
Introduction to Prime Numbers
Introduction to Prime NumbersIntroduction to Prime Numbers
Introduction to Prime Numbers
Luke Dunn
 
GCSE-Surds.pptx
GCSE-Surds.pptxGCSE-Surds.pptx
GCSE-Surds.pptx
BimboBbsax
 
data handling class 8
data handling class 8data handling class 8
data handling class 8
HimakshiKava
 
Multiplying Fractions
Multiplying FractionsMultiplying Fractions
Multiplying Fractions
Lynne Crowe
 
Pseudorandom number generators powerpoint
Pseudorandom number generators powerpointPseudorandom number generators powerpoint
Pseudorandom number generators powerpoint
David Roodman
 
I have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdfI have another assignment due for an advance java programming class .pdf
I have another assignment due for an advance java programming class .pdf
FORTUNE2505
 
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHONmodule 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
FahmaFamzin
 
Math class 8 data handling
Math class 8 data handling Math class 8 data handling
Math class 8 data handling
HimakshiKava
 
MATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdf
MATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdfMATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdf
MATHEMATICS 4 - PRIME AND COMPOSITE NUMBERS.pdf
Jay Cris Miguel
 
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docxHierarchies of LifeExperiment 1 Classification of Common Objects.docx
Hierarchies of LifeExperiment 1 Classification of Common Objects.docx
pooleavelina
 
Counting (Notes)
Counting (Notes)Counting (Notes)
Counting (Notes)
roshmat
 
Vpet sd-1.25.18
Vpet sd-1.25.18Vpet sd-1.25.18
Vpet sd-1.25.18
Thinkful
 
Applied 40S March 12, 2009
Applied 40S March 12, 2009Applied 40S March 12, 2009
Applied 40S March 12, 2009
Darren Kuropatwa
 
CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1
johnnygoodman
 

Recently uploaded (20)

Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Navigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdfNavigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdf
Applitools
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Driving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital AgeDriving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital Age
SatishKumar2651
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
The Elixir Developer - All Things Open
The Elixir Developer - All Things OpenThe Elixir Developer - All Things Open
The Elixir Developer - All Things Open
Carlo Gilmar Padilla Santana
 
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEMGDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
philipnathen82
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?
Amara Nielson
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Gojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service BusinessGojek Clone App for Multi-Service Business
Gojek Clone App for Multi-Service Business
XongoLab Technologies LLP
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Navigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdfNavigating EAA Compliance in Testing.pdf
Navigating EAA Compliance in Testing.pdf
Applitools
 
Programs as Values - Write code and don't get lost
Programs as Values - Write code and don't get lostPrograms as Values - Write code and don't get lost
Programs as Values - Write code and don't get lost
Pierangelo Cecchetto
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Sequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptxSequence Diagrams With Pictures (1).pptx
Sequence Diagrams With Pictures (1).pptx
aashrithakondapalli8
 
Driving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital AgeDriving Manufacturing Excellence in the Digital Age
Driving Manufacturing Excellence in the Digital Age
SatishKumar2651
 
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdfHow to avoid IT Asset Management mistakes during implementation_PDF.pdf
How to avoid IT Asset Management mistakes during implementation_PDF.pdf
victordsane
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEMGDS SYSTEM | GLOBAL  DISTRIBUTION SYSTEM
GDS SYSTEM | GLOBAL DISTRIBUTION SYSTEM
philipnathen82
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?AI in Business Software: Smarter Systems or Hidden Risks?
AI in Business Software: Smarter Systems or Hidden Risks?
Amara Nielson
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
Ad

Introduction to Genetic Algorithms with Python - Hello World!