I am Python noob trying to learn a coding exercise I found online. I have a number of chicken nuggets that I need to purchase and the nuggets come in three different pack sizes (6,9, and 20).
I need to setup up a function that optimizes my purchase (maximizing the 20packs first, then the 9 pack, then the 6 pack). The first priority is making sure there is no remainder and THEN optimizing for pack size. so for 139 the answer would be 5 20-packs, 3 9-packs, and 2 6-packs. Currently I've done the function using a series of nested while loops but I know there has to be a much more elegant solution.
Thanks for your help!
def nuggets(nuggs_needed):
packs = [6,9,20]
twenty_counter = nuggs_needed//20 # Start 20 pack counter with largerst divisable number#
ttl_nuggs=0
while twenty_counter>=0:
ttl_nuggs = 0
twenty_nuggs_ttl = twenty_counter*20 #total nuggest for 20 pack#
new_nuggs_needed = nuggs_needed-twenty_nuggs_ttl #remaining nuggs after 20 pack#
nine_counter = new_nuggs_needed//9
while nine_counter>=0:
nine_nuggs_ttl = nine_counter*9
ttl_nuggs = twenty_nuggs_ttl+nine_nuggs_ttl
new_nuggs_needed = nuggs_needed-ttl_nuggs
six_counter = new_nuggs_needed//6
while six_counter>=0:
six_nuggs_ttl = six_counter*6
ttl_nuggs = twenty_nuggs_ttl+six_nuggs_ttl+nine_nuggs_ttl
new_nuggs_needed = nuggs_needed-ttl_nuggs
print '{0} 20packs, {1} 9packs, {2} 6packs = {3}total nuggets'.format(twenty_counter,nine_counter,six_counter,ttl_nuggs)
if ttl_nuggs == nuggs_needed:
print 'Thats it: {0} 20packs, {1} 9packs, {2} 6packs = {3}total nuggets'.format(twenty_counter,nine_counter,six_counter,ttl_nuggs)
print 'Hooray!'
break
six_counter-=1
if ttl_nuggs == nuggs_needed:
break
nine_counter-=1
if ttl_nuggs == nuggs_needed:
break
twenty_counter-=1
nuggets(139)