I hope this is not homework, the code below can solve your problem.
animals=[]
preys=[]
with open('AquaticFoodWeb.txt','r') as f:
for line in f:
animals.append(line.split()[0])
preys.append(line.split()[-1])
height = {}
length = len(preys)
rank = 0
while preys != [None]*length:
for index,(animal,prey) in enumerate(zip(animals,preys)):
if prey not in animals:
try:
if height[prey] < rank:
height[prey] = rank
except KeyError:
height[prey] = 0
height[animal] = height[prey] + 1
preys[index] = None
animals[index] = None
rank += 1
print sorted(height.items(),key = lambda x:x[1],reverse=True)
Output:
[('Lobster', 4), ('Bird', 4), ('Fish', 3), ('Whelk', 3), ('Crab', 3),('Mussels', 2),
('Prawn', 2), ('Zooplankton', 1), ('Limpets', 1),('Phytoplankton', 0), ('Seaweed', 0)]
source
share