looping through possible combinations of McNuggets packs of 6, 9 and 20

Baba raoulbia at gmail.com
Mon Aug 16 22:18:39 CEST 2010


well i still believe that the key is the smallest sized pack and
there's no need to go into higher mathematics to solve this problem.
I think below code works within the limits of the exercise which
states to look at a maximum range of 200 in order not to search
forever.

packages=[2,103,105]
min_size=min(packages[0],packages[1],packages[2])
cbc=0 #cbc=can_buy counter
for n_nuggets in range(1,200):
   if cbc>=min_size:
      break
   can_buy=False
   for a in range (n_nuggets/packages[0]+1):
      for b in range (n_nuggets/packages[1]+1):
         for c in range (n_nuggets/packages[2]+1):
            #print "trying for %d: %d %d %d" % (n_nuggets,a,b,c)
            if packages[0]*a+packages[1]*b+packages[2]*c==n_nuggets:
                can_buy=True
                break
   if can_buy==True:
      cbc+=1
   else:
      cbc=0
      sol=n_nuggets
print sol



Baba



More information about the Python-list mailing list