Learning Objectives?
In this set of Python challenges we will investigate the use of two data structures used in programming to represent data:
- We will use an array/list to represent a food chain.
- We will use a graph to represent a food web.
Did you know?
A food chain shows the different organisms that live in a habitat, and what eats what.
A predator is an animal that eats other animals, and the prey is the animal that gets eaten by the predator.
Here is an example of food chain:
In the food chain above:
- the frog is a predator and the grasshopper is its prey.
- the snake is a predator and the frog is its prey.
Python Challenge
For this challenge you will write a Python program that stores the organisms a food chain using a list.
You program will randomly pick two organisms from the food chain. One for the player, one for the computer.
The program will find out the positions of these organisms in the given food chain. (This is known as the trophic level of an organism which is the position it holds in a food chain).
The program will compare both positions, the player with the highest position in the food chain will win the game.
We have started the code for you. Complete this code to:
- Randomly select the “computer organism” from the list.
- Make sure that both selected organisms are different.
- Compare the positions of both organisms to decide who, between the computer and the player, wins the round.
Food Web
When all the food chains in a habitat are joined up together they form a food web. Here is an example of a food web:
Although it looks complex, it is just several food chains joined together. Here are some of the food chains in this food web:
To represent a food web we will use a different data structure called a graph.
Most programming languages do provide direct support for graphs as a data type. Python for instance does not have a graph data structure. However, graphs can be built out of lists and dictionaries. For instance, here is a graph to represent the above food web:
foodWeb = {'insect': ['grass'], 'rabbit': ['grass'], 'slug': ['grass'], 'thrush': ['slug','insect'], 'vole': ['insect'], 'frog': ['insect'], 'hawk': ['frog','vole','thrush'], 'fox': ['rabbit','frog','vole']}
This graph is a dictionary where the keys are the nodes of the graph. For each key, the corresponding value is a list containing the nodes that are connected by a direct arc from this node. Note that this is a directed graph as each link/arc has a direction.
Python Code
Compete the code below to:
- Find out if the computer organism and the player organism are linked (Direct link or indirect link).
- If a link/path is detected, decide who, between the computer and the player, wins the game.
Tip: Use the find_path() algorithm described on https://www.python.org/doc/essays/graphs/
Solution...
The solution for this challenge is available to full members!Find out how to become a member:
➤ Members' Area