Notes about the Problem: Animals can only eat things beside them.
Animals always eat to their LEFT before eating to their RIGHT. Always the LEFTMOST animal capable of eating will eat before any others.
Any other things you may find at the zoo (which are not listed above) do not eat anything and are not edible.
Can you help me? Why I am getting: "Execution Timed Out"
KATA: https://www.codewars.com/kata/5902bc7aba39542b4a00003d/python
What can I do with IndexError?
My solutions:
animal_dict = {'antelope': 'grass',
'big-fish': 'little-fish',
'bug': 'leaves',
'bear': ['big-fish', 'bug', 'chicken', 'cow', 'leaves', 'sheep'],
'chicken': 'bug',
'cow': 'grass',
'fox': ['chicken', 'sheep'],
'giraffe': 'leaves',
'lion': ['antelope', 'cow'],
'panda': 'leaves',
'sheep': 'grass'}
def who_eats_who(zoo):
if zoo == '':
return ['', ''] #The condition calls for this
process = []
units = zoo.split(',') #from str to lst
process.append(zoo) #The condition calls for this
try:
while True:
for i, k in enumerate(units):
if k in animal_dict:
#check left eating
if units[i - 1] in animal_dict[units[i]] and i != 0:
process.append(f'{units[i]} eats {units[i - 1]}')
del units[i - 1]
break
#check right eating
elif units[i + 1] in animal_dict[units[i]]:
process.append(f'{units[i]} eats {units[i + 1]}')
del units[i + 1]
break
else:
continue
except IndexError:
x = ','.join(units)
process.append(x)
return process