Recursive path generation
In this tutorial, the goal is to recursively generate a family of paths.
Python yield
This section is an introduction to the yield command in python which is used to create generators
The goal of the stupid_generator function is to list integers smaler than . But instead of returning a list, it returns a generator of the list. Compare with this other function.
To get the objects created by stupid_generator, you need to explicitly transform it to a list. You can also loop through the object directly without creating the list (that is why it is useful!)
The instructions inside stupid_generator are not executed at the time of initial call but only when you start looping through it.
The following function gives you a more explicit example. The yield instruction acts as a "pause" on the execution, the rest of the code is executed only when the method next is called.
Exercise: implement the following function whose goal is to generate the first prime numbers. You can check your function with the tests below.
To test if a number is prime, you can do
In all previous examples, the generator stops by itself after some time. But you can also do infinite generators. Then, it is up to the caller to stop the generation.
Implement the following functions (you are given the documentation in the way we write it in Sage)
Path on the grid
Here is a python class to represent a path on the 2D-grid. A path is a list of step (2D vectors). We have implemented a basic printout and a plot. Look at the class and the examples.
Exercise: create a path that draws a 2x2 square.
The goal of the tutorial is to generate the set of all possible paths following certain constraints. We will use two kinds of steps:
up steps (1,1)
down steps (1,-1)
We first generate the set of paths of a given length. Here is for example the list of paths of length 2.
Here are the functions generating paths of lengths 0, 1, and 2.
Follow the same idea and write getPaths3.
Now that you get the idea, write a recursive function that generates the set of all paths of a given size .
If the given is negative, the function should not return anything (the empty path is of size 0!). Test if your function is well adapted to this rule.
More difficult now we want all paths that ends on a given point
Hint answer first the following questions:
If my path ends in with an up step, where was is before the up step? Same question with a down step.
What are the positions I can never get to? What should I do in this case?
When should I return the empty path?
Last step! Now, we want to generate the paths that end in but are ALSO never going under the line .
Do you know these numbers?
These objects actually already exist in Sage. They are called Dyck words. You can look through their methods and implementation.