I've come across a situation where my python code behaves differently in similar cases. Here's the code:
import time
def greedy_cow_transport(cows,limit=10):
weights = []
for weight in cows.values():
weights.append(weight)
weights.sort(reverse=True)
cows_copy = cows.copy()
all_trips = []
while (len(weights) > 0):
avail_weight = limit
curr_trip = []
for weight in weights:
if weight <= avail_weight:
for n, w in cows_copy.items():
if weight == w:
curr_trip.append(n)
weights.remove(weight)
cows_copy.pop(n, None)
avail_weight -= w
break
all_trips.append(curr_trip)
return all_trips
cows = {'Lola': 2, 'Oreo': 2, 'Millie': 2, 'Betsy': 2, 'Moo Moo': 2, 'Milkshake': 2, 'Herman': 2, 'Florence': 2, 'Maggie': 2, 'Henrietta': 2}
limit=100
print(cows)
print(greedy_cow_transport(cows))
Instead of greedy_cow_transport returning the 2 list of lists of 5 members, it return 3 different lists of 5 3 2 members. Please explain why its happening? I know, I might be missing some subtle detail but I need help. Can't figure out the error. Thanks.