Control flow
Here's the next bit of code we're going to optimise:
if random.random() < 0.5:
agents[0][0] += 1
else:
agents[0][0] -= 1
if random.random() < 0.5:
agents[0][1] += 1
else:
agents[0][1] -= 1
if random.random() < 0.5:
agents[0][0] += 1
else:
agents[0][0] -= 1
if random.random() < 0.5:
agents[0][1] += 1
else:
agents[0][1] -= 1
This moves our coordinates twice. Can you work out how to do this for all the agents with a new loop? (don't use the one that appends the coordinates – that would be efficient, but if we start doing stuff inside one loop new agents made at the start won't be able to interact with agents not yet created; we need to create all agents before they start interacting, so write a fresh loop).
Note that if our for-loop looks like this:
for i in range(num_of_agents):
Each agent can be referred to as:
agents[i]
So the y location can be referred to as:
agents[i][0]
Given this, can you work out how to make the code above work for every agent?
Once you've done this, you can delete all the code dealing with the original second agent's coordinates, we no longer need it.
You can also comment out the Pythagoras code for the moment: we'll come back to that next practical.
"Commenting out" involves temporarily putting a #
at the front of each line you don't want to
run, or '''
on a line before and after a section of code your don't want to run. Comment out the Pythagoras code for the
moment as it demands two agents, and we're concentrating on getting the code to run for many more.
Now, at the moment we're only displaying two or three agents. See if you can get the following lines running for multiple agent coordinates. Which bits need to run inside a loop, which need to run only once, and which can we get rid of?
matplotlib.pyplot.ylim(0, 99)
matplotlib.pyplot.xlim(0, 99)
matplotlib.pyplot.scatter(agents[0][1],agents[0][0])
matplotlib.pyplot.scatter(agents[1][1],agents[1][0])
matplotlib.pyplot.show()
Note we've removed the line to highlight the most easterly coordinates; you can add it back in later if you like, but it's not important.
Once you've got that working, go to the next section, where we'll look at making the agents take more than two steps.