O'Reilly logo

Genetic Algorithms and Machine Learning for Programmers by Frances Buontempo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Let’s Save the Turtle

The goal is to help the turtle escape the bag you saw earlier here. The easiest way is to make him move in a straight line. He might then march through the sides of the bag. You can constrain him to only escape through the top, but let him go where he wants for now. When he’s out, you need to get him to stop. But how do you know when he’s out? The left edge of the bag is at -35, and the right is at +35. The bottom and top are also at -35 and +35, respectively. This makes checking his escape attempts easy:

 def​ ​escaped​(position):
  x = int(position[0])
  y = int(position[1])
 return​ x < -35 ​or​ x > 35 ​or​ y < -35 ​or​ y > 35

Now all you need to do is set him off and keep him going until he’s out: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required