Functions
Remove the commenting out of the Pythagorian code, and let's look at it. Here it is:
answer = (((agents[0][0] - agents[1][0])**2) + ((agents[0][1] - agents[1][1])**2))**0.5
print(answer)
Ideally, we want this code to work for any arbitrary pair of agents. Ultimately we'll pass every pair through this to see how far apart they all are.
In order to do this, let's turn this code into a function. At the top of your code, after the import statements and before anything else, write the following function declaration:
def distance_between(agents_row_a, agents_row_b):
This function takes in two arbitary agents (at the moment, two rows in our agents list, each containing two values), and will return the distance between them. To start with, we are going to call the function from the code at the bottom of our program (just because it's out of the way), like this:
distance = distance_between(agents[0], agents[1])
print(distance)
Ultimately we'll get it working for all agent combinations, but for the moment we'll just use two agents. Note the
slight of hand here: agents[0]
is being allocated the name agents_row_a
within the
function: this means that whereas before we would get the y
value out as
agents[0][0]
we'd now talk about agents_row_a[0]
. Make sure you understand why we've dropped a dimensions before moving on.
Can you get this function working? Think about what is being passed in (better still, inside the function,
use type()
to find out). Given this, how do you re-write the Pythagoras code? How would we test the
code to make sure it is working well?
Once you've got that working, go on to the next part, where we'll do it for all agent combinations.
- The code
- This page
- Running our function <-- next