Given a dictionary of cows and their weight:
cows = {'Betsy': 9, 'Oreo': 6, 'Herman': 7, 'Florence': 2, 'Maggie': 3, 'Moo Moo': 3, 'Milkshake': 2, 'Lola': 2, 'Millie': 5, 'Henrietta': 9}
I want to get a list of lists to move all cows, each nested list of cow's a total weight <= 10, hence to first two trips will have just Betsy and Henrietta:
The answer for GREEDY COW TRANSPORT:
[['Betsy'], ['Henrietta'], ['Herman', 'Maggie'], ['Oreo', 'Moo Moo'], ['Millie', 'Florence', 'Milkshake'], ['Lola']]
Here is my code that took too long in a net grader:
def greedy_cow_transport(cows,limit=10):
train = []
cart = []
# get tuples from dictionary key ordered by value high to low
CowTupleList = sorted(cows.items(), key=lambda x: x[1], reverse = True)
# put cow names in list order high to low to loop over
names = []
for i in range(len(cows)):
names.append(CowTupleList[i][0])
train = []
while sum(cows.values()) > 0:
cart = []
total = 0
for cow in names:
if cows[cow] != 0 and cows[cow] + total <=limit:
cart.append(cow)
total += cows[cow]
cows[cow] = 0
train.append(cart)
return train
This took too much time for the online grader, so I failed. Can this be done in only a few lines?