2024-heraklion-scientific-p.../notebooks/walker/Step_1_classes/solution/Step_1_classes.ipynb
2024-08-27 15:52:41 +03:00

118 KiB

2. Rewrite the code to look like it would in your wildest dreams!

How could you restructure the interface of the walker library so that the functionality stays the same, but the code is less smelly?

  1. could this code work better/more efficiently as a class?
    • e.g. walker = Walker(...)
  2. how should the setup/initialization work?
    • e.g. which parameters would you pass to instantiate the Walker class? How do you pass them to the class?
  3. which functions should be part of the class?
    • e.g. is sample_next_step a method of Walker? Is create_context_map a method of Walker? How about plot_trajectory? If so, call them with walker.sample_next_step()
  4. what would the import statement look like?

Important: We are not asking you to implement the changes in walker.py! Imagine the new interface, and write the code that would use it in the next cell. Of course it won't run (yet)

Here are some things to keep in mind:

  • Which things will you do a lot? They should be easy to do. The interface for doing those things should be simple.
  • Which things should be modifiable from external code?
  • As a rule of thumb, think about how it sounds when you read it aloud
    • “Giving orders”-style
    • “Telling a story“-style

For inspiration think about how you call code from other libraries. Here is an example of instantiating an object and calling one of its methods:

import scipy as sp

#  Sampling from a gaussian with specific mean and sd:
# Create a Gaussian (normal) distribution object
gaussian_dist = sp.stats.norm(loc=mean, scale=sd)
# Sample 10 values from the Gaussian distribution
samples = gaussian_dist.rvs(size=10)
In [1]:
%matplotlib inline

from walker import Walker, plot_trajectory
In [2]:
# Create a Walker instance
walker = Walker(sigma_i=3, sigma_j=4, size=200, map_type='hills')

# Sample a next step 1000 times
i, j = 100, 50
trajectory = []
for _ in range(1000):
    i, j = walker.sample_next_step(i, j)
    trajectory.append((i, j))
In [3]:
plot_trajectory(trajectory, walker.context_map)
In [ ]:

In [ ]: