Stop learning alone!

Learn faster and stay on-track by joining this free class with other self-learners.

Register for MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming now.

MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming

Class length: 24 weeks. Start anytime.

Creator: duallain

Status: Established

Join this class!

Lesson 3: Assignment 1

assignment. Remember to take a look at the template provided.

Homework Submissions

61 total

mgoff11 (Self-grade: Outstanding)
Submitted 4 days ago | Permalink | Time spent: 1 minute
#Problem Set 2a
#Michael

a=6
b=9
c=20
candidate=0
bestSoFar=1

for n in range(1,50):
    for i in range(0,n/a+1):
        for j in range(0,n/b+1):
            for k in range(0,n/c+1):
                if a*i+b*j+c*k==n:
                    break
            if a*i+b*j+c*k==n:
                break
        if a*i+b*j+c*k==n:
            break
    if a*i+b*j+c*k==n:
        candidate+=1
    else:
        candidate=0
        bestSoFar=n
    if candidate==6:
        break

print 'Largest number of McNuggets that cannot be bought in exact quantity: '+str(bestSoFar)
        







#Problem Set 2b
#Michael 

bestSoFar = 0     
                  
packages = (2,4,6)   
a=packages[0]
b=packages[1]
c=packages[2]

for n in range(1, 150):   
    for i in range(0,n/a+1):
        for j in range(0,n/b+1):
            for k in range(0,n/c+1):
                if a*i+b*j+c*k==n:
                    break
            if a*i+b*j+c*k==n:
                break
        if a*i+b*j+c*k==n:
            break
    if a*i+b*j+c*k==n:
        candidate+=1
    else:
        candidate=0
        bestSoFar=n
    if candidate==a:
        break

if candidate<a:
    print 'The largest number of McNuggets that cannot be bought in exact quantity is greater than 150.'
else:
    print 'Given package sizes '+str(a)+', '+str(b)+', and '+str(c)+', the largest number of McNuggets that cannot be bought in exact quantity is: '+str(bestSoFar)

        
        
            
wolfei (Self-grade: Pretty good)
Submitted 2 months ago | Permalink | Time spent: 10 days

Programming rawr

##### Assignment 2              #####
#####################################
##### Problem Set 1             #####  
##### Name: Wolfei              #####  
##### Collaborators: Internet   ##### 
##### Time: pending             #####


##    6       9       20
##    12      18      20      50
##    6       45      0       51
##    12      0       40      52
##    24      9       20      53
##    9       0       0       54
##    6       9       40      55
##
##    We can easily derive the next amounts (56....65) like this
##    (12 + 18 + 20) + 6  =  56
##    (6 + 45 + 0 ) + 6   =  57
##    (12 + 0 + 40) + 6   =  58
##    (24 + 9 + 20) + 6   =  59
##    (9 + 0 + 0) +  6    =  60
##    (6 + 9 + 40) + 6    =  61
##
##    Now we use the newly created and add 6 to them as we did with
##    original ones
##
##    [(12 + 18 + 20) + 6] + 6 =  62
##    [(6 + 45 + 0 ) + 6] + 6 =   63
##    [(12 + 0 + 40) + 6] + 6 =   64
##    [(24 + 9 + 20) + 6] + 6 =   65
    

##### Problem Set 2             #####  
##### Name: Wolfei              #####  
##### Collaborators: Internet   ##### 
##### Time: pending             #####

##The theorem is true because once we have found how to create x, x+1, ....x+5
##we can easily find the next combinations of macnuggets that will lead us to
##higher quantities by adding 6 to x, x+1, ...x+5



##### Problem Set 3             #####  
##### Name: Wolfei              #####  
##### Collaborators: Internet   ##### 
##### Time: 3 weeks             #####


def Problem3():
    x = []
    n = 1
    while n < 200+1:
        if lolcakeA(n) or lolcakeB(n) or lolcakeC(n) == 1:
##            print "saving n", n
            n += 1
        else:
##            print "n isnt good", n
            x += [n]
            n += 1

    print "Largest number of McNuggets that cannot be bought in exact quantity is :"
    raw_input()
    print x[-1]


def lolcakeA(x):
    a = 0
    b = 0
    c = 0
     
    for a in range (0,8+1):
        if 6*a+9*b+20*c == x:
            return 1
        else:
            for b in range (0,5+1):
                if 6*a+9*b+20*c == x:
                    return 1
                else:    
                    for c in range (0,3+1):
                        if 6*a+9*b+20*c == x:
                            return 1
    return 0
                            
    
def lolcakeB(x):
    a = 0
    b = 0
    c = 0
   
    for b in range (0,40+1):
        if 6*a+9*b+20*c == x:
            return 1
        else:
            for c in range (0,40+1):
                if 6*a+9*b+20*c == x:
                    return 1
                else:    
                    for a in range (0,40+1):
                        if 6*a+9*b+20*c == x:
                            return 1
    return 0
    
def lolcakeC(x):
    a = 0
    b = 0
    c = 0

    for c in range (0,40+1):
        if 6*a+9*b+20*c == x:
            return 1
        else:
            for a in range (0,40+1):
                if 6*a+9*b+20*c == x:
                    return 1
                else:    
                    for b in range (0,40+1):
                        if 6*a+9*b+20*c == x:
                            return 1
    return 0


##### Problem Set 4             #####  
##### Name: Wolfei              #####  
##### Collaborators: Internet   ##### 
##### Time: pending             #####

def Problem4():
    
    
    lista = []
    n = 1
    x = input(" tell me the lowest number:  ")
    y = input(" tell me the number in the middle:  ")
    z = input(" tell me the highest number:  ")
    packages = (x, y, z)
    while n < 200+1:
        if lolcakeA2(n,x,y,z) or lolcakeB2(n,x,y,z) or lolcakeC2(n,x,y,z) == 1:
            n += 1
        else:
            lista += [n]
            n += 1

    print ""
    print "Given package sizes",  x , y, "and",  z, 
    print "the largest number of McNuggets that cannot be bought in exact quantity is:", lista[-1] 
      
        

def lolcakeA2(n, x, y, z):
    """ n = number you want to check,  [xyz] are number of packages of McNuggets"""
    x = 0
    y = 0
    z = 0
     
    for x in range (0,40+1):
        if 6*x+9*y+20*z == n:
            return 1
        else:
            for y in range (0,40+1):
                if 6*x+9*y+20*z == n:
                    return 1
                else:    
                    for z in range (0,40+1):
                        if 6*x+9*y+20*z == n:
                            return 1
    return 0

def lolcakeB2(n, x, y, z):
    """ n = number you want to check,  [xyz] are number of packages of McNuggets"""
    x = 0
    y = 0
    z = 0
     
    for y in range (0,40+1):
        if 6*x+9*y+20*z == n:
            return 1
        else:
            for z in range (0,40+1):
                if 6*x+9*y+20*z == n:
                    return 1
                else:    
                    for x in range (0,40+1):
                        if 6*x+9*y+20*z == n:
                            return 1
    return 0

def lolcakeC2(n, x, y, z):
    """ n = number you want to check,  [xyz] are number of packages of McNuggets"""
    x = 0
    y = 0
    z = 0
     
    for z in range (0,40+1):
        if 6*x+9*y+20*z == n:
            return 1
        else:
            for x in range (0,40+1):
                if 6*x+9*y+20*z == n:
                    return 1
                else:    
                    for y in range (0,40+1):
                        if 6*x+9*y+20*z == n:
                            return 1
    return 0
carmichael22 (Self-grade: Pretty good)
Submitted 3 months ago | Permalink | Time spent: 6 hours
#Rob Carmichael
#Problem Set 2

#Problem 1

##a=6
##b=9
##c=20
##
##for n in range(50,56):
##    for d in range(0,n/a+1):
##        for e in range(0,n/b+1):
##            for f in range(0,n/c+1):
##                if a*d+b*e+c*f==n:
##                    print "a*%d+b*%d+c*%d==%d" % (d,e,f,n)
##
# Not sure how to exit for loops after we initially solve the equation.
# As is the program continues to iterate.

#Problem 2
# Theorem is true because if you can buy nuggets in six consecutive integers,
# then you can just buy a multiple of six for any of those numbers.


#Problem 3

##a=6
##b=9
##c=20
##cantget=[]
##consecutivepasses=0
##
##for n in range(1,150):
##    test = False
##    if consecutivepasses==6:
##        break
##    for d in range(0,n):
##        for e in range(0,n):
##            for f in range(0,n):
##                if a*d+b*e+c*f==n:
##                    test = True
##    if test:
##        consecutivepasses +=1
##    if not test:
##        bestsofar=n
##        cantget.append(n)
##        consecutivepasses = 0
##print "Largest number of McNuggets that cannot be bought in exact quantity: "\
##, str(bestsofar)+"."
##print "Here's the set of numbers of nuggets you can\'t get at McDonalds: ", cantget,'.'
##print consecutivepasses
                    
#Problem 4

### template of code for Problem 4 of Problem Set 2, Fall 2008
###

    # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
   # variable that contains package sizes
  # only search for solutions up to size 150
    ## complete code here to find largest size that cannot be bought
    ## when done, your answer should be bound to bestSoFar

def numberNuggets(x,y,z):
    bestSoFar = 0
    packages = (x,y,z)
    consecutive = 0
    for n in range(1,150):
        if consecutive==min(packages):
            break
        test=False
        for d in range(0,n):
            for e in range(0,n):
                for f in range(0,n):
                    if x*d+y*e+z*f==n:
                        test=True
        if test:
            consecutive+=1
        else:
            bestSoFar=n
            consecutive=0
    print "Given package sizes %d, %d, and %d, the largest number of McNuggets that cannot be bought \
in exact quantity is: %d." % (x,y,z,bestSoFar)


    
   
sebrenner (Self-grade: Outstanding)
Submitted 3 months ago | Permalink | Time spent: 5 hours
#!/usr/local/bin/python

##	Problem 1.
	##	Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 McNuggets, by finding solutions to the Diophantine equation. You can solve this in your head, using paper and pencil, or writing a program. However you chose to solve this problem, list the combinations of 6, 9 and 20 packs of McNuggets you need to buy in order to get each of the exact amounts.  Given that it is possible to buy sets of 50, 51, 52, 53, 54 or 55 McNuggets by combinations of 6, 9 and 20 packs, show that it is possible to buy 56, 57,..., 65 McNuggets. In other words, show how, given solutions for 50-55, one can derive solutions for 56-65.  If it is possible to buy x,x+1,...,x+5 sets of McNuggets,for some x,then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs.

	##	6a + 9b + 20c = n
	##	6a = n - 9b -20c 
	##	a = n/6 - 3/2b - 10/3c
	
	# 49 = (2*20) + (0*6) + (1*9)  # just curious
	# 50 = (1*20) + (2*6) + (2*9)
	# 51 = (0*20) + (4*6) + (3*9)
	# 52 = (2*20) + (2*6) + (0*9)
	# 53 = (1*20) + (1*6) + (3*9)
	# 54 = (0*20) + (0*6) + (6*9)
	# 55 = (2*20) + (1*6) + (1*9)
##------
	# 56 = (1*20) + (3*6) + (2*9)
	# 57 = (0*20) + (4*6) + (3*9)
	# 58 = (2*20) + (3*6) + (0*9)
	# 59 = (1*20) + (2*6) + (3*9)
	# 60 = (0*20) + (1*6) + (6*9)
	# 61 = (2*20) + (2*6) + (1*9)
	# 62 = (1*20) + (4*6) + (2*9)
	# 63 = (0*20) + (6*6) + (3*9)
	# 64 = (2*20) + (4*6) + (0*9)
	# 65 = (1*20) + (3*6) + (3*9)
	
#	Problem 2: Explain, in English, why this theorem is true.
## For this type of problem, if you can find a string of sequential numbers that is as long as the smallest counting unit then you can count to any subsequent number by adding this smallest counting unit a member of this base sequential series. Wow. 


# Problem 3
#
	#	Write an iterative program that finds the largest number of McNuggets that cannot be bought in exact quantity. Your program should print the answer in the following format (where the correct number is provided in place of <n>):

#	largest number of McNuggets that cannot be bought in exact quantity:
	#	Hint: your program should follow the outline above.
	#	Hint: think about what information you need to keep track of as you loop through possible ways of buying exactly n McNuggets. This will guide you in deciding what state variables you will need to utilize.
	#	Save your code for Problem 3 in ps2a.py.



#	Using this theorem, we can write an exhaustive search to find the largest number of McNuggets that cannot be bought in exact quantity. The format of the search should probably follow this outline:
#	Hypothesize possible instances of numbers of McNuggets that cannot be purchased exactly, starting with 1
#For each possible instance, called n,
	#Test if there exists non-negative integers a, b, and c, such that 6a+9b+20c = n. (This can be done by looking at all feasible combinations of a, b, and c) 
	#If not, n cannot be bought in exact quantity, save n
#	When you have found six consecutive values of n that in fact pass the test of having an exact solution, the last answer that was saved (not the last value of n that had a solution) is the correct answer, since you know by the theorem that any amount larger can also be bought in exact quantity

print 'Problem 3'
print

def is_n_solveable(n):
	a = 0
	b = 0
	c = 0
	for a in range(10):
		#print 'in a for loop. a:', a,'b:',b,'c:',c,'n:',n
		if 6*a + 9*b + 20*c == n:
			return 1
			#ns_passed_test.append(n)
			#print n, "passed"	
		for b in range(10):
			#print 'in b for loop. a:', a,'b:',b,'c:',c,'n:',n
			if 6*a + 9*b + 20*c == n:
				return 1
				#ns_passed_test.append(n)
				#print n, "passed"
			for c in range(10):
				#print 'in c for loop. a:', a,'b:',b,'c:',c,'n:',n
				if 6*a + 9*b + 20*c == n:
					return 1
					#ns_passed_test.append(n)
					#print n, "passed"
	return 0

counter = 0
highest_number_to_test = 43

for n in range(highest_number_to_test+7):
	if is_n_solveable(n):
		counter = counter + 1
	else:
		counter = 0

	if counter == 6:
		print n-6, "is highest number of nuggets that can not be ordered in a 6,9,20 combo."
	elif n == highest_number_to_test+7:
		print 'The highest number of noggest that cannot be ordereed in a in 6,9,20 combo is greater than', highest_number_to_test

print 
print 'End of problem 3'
print 

##	Problem 4.
##	Assume that the variable packages is bound to a tuple of length 3, the values of which specify the sizes of the packages, ordered from smallest to largest. Write a program that uses exhaustive search to find the largest number (less than 200) of McNuggets that cannot be bought in exact quantity. We limit the number to be less than 200 (although this is an arbitrary choice) because in some cases there is no largest value that cannot be bought in exact quantity, and we don't want to search forever. Please use ps2b_template.py to structure your code.
##	Have your code print out its result in the following format:
##	"Given package sizes <x>, <y>, and <z>, the largest number of McNuggets that cannot be bought in exact quantity is: <n>"

##	Test your program on a variety of choices, by changing the value for packages. Include the case (6,9,20), as well as some other test cases of your own choosing.

##	This problem took 4-5 hours over the course of a couple days.

print 'Problem 4'
print 

packages = (6, 9, 20)

def is_n_solveable(n,packages):
	"""Takes a value n and a 3-member tuple.  The tuple describes the three package size, e.g., 6, 9, 20 McNuggets. The function tests whether any combination of the packages will add up to exactly n."""

	a = 0
	b = 0
	c = 0
	for a in range(10):
		#print 'in a for loop. a:', a,'b:',b,'c:',c,'n:',n
		if packages[0]*a + packages[1]*b + packages[2]*c == n:
			return 1
			#ns_passed_test.append(n)
			#print n, "passed"	
		for b in range(10):
			#print 'in b for loop. a:', a,'b:',b,'c:',c,'n:',n
			if packages[0]*a + packages[1]*b + packages[2]*c == n:
				return 1
				#ns_passed_test.append(n)
				#print n, "passed"
			for c in range(10):
				#print 'in c for loop. a:', a,'b:',b,'c:',c,'n:',n
				if packages[0]*a + packages[1]*b + packages[2]*c == n:
					return 1
					#ns_passed_test.append(n)
					#print n, "passed"
	return 0

counter = 0	

x = 6
y = 9
z = 20

for n in range(100):
	if is_n_solveable(n, packages):
		counter = counter + 1
	else:
		counter = 0
	if counter == packages[0]:
		print 'Given package sizes', packages[0], ',', packages[1], ', and', packages[2], 'the largest number of McNuggets that cannot be bought in exact quantity is:', n-packages[0]
print		
print 'end of Problem 4'
print 

		
print 'Problem 4.1: the prescribed format.'

bestSoFar = 0     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity

packages = (6,9,20)   # variable that contains package sizes
packages_1 = (16,19,20)   # variable that contains package sizes
packages_2 = (7,15,20)   # variable that contains package sizes
packages_3 = (9,12,20)   # variable that contains package sizes
packages_4 = (11,16,20)   # variable that contains package sizes
packages_5 = (4,9,16)   # variable that contains package sizes

six_packages = (packages,packages_1,packages_2,packages_3,packages_4,packages_5)
packages_to_test = len(six_packages)

def is_n_solveable(n,packages):
	"""Takes a value n and a 3-member tuple.  The tuple describes the three package size, e.g., 6, 9, 20 McNuggets. The function tests whether any combination of the packages will add up to exactly n."""
	a = 0	# Initialize the multiples of each package size.
	b = 0
	c = 0
	for a in range(10):
		# print 'in a for loop. a:', a,'b:',b,'c:',c,'n:',n
		# print packages[0]
		
		if packages[0]*a + packages[1]*b + packages[2]*c == n:
			return 1
			#ns_passed_test.append(n)
			#print n, "passed"	
		for b in range(10):
			#print 'in b for loop. a:', a,'b:',b,'c:',c,'n:',n
			if packages[0]*a + packages[1]*b + packages[2]*c == n:
				return 1
				#ns_passed_test.append(n)
				#print n, "passed"
			for c in range(10):
				#print 'in c for loop. a:', a,'b:',b,'c:',c,'n:',n
				if packages[0]*a + packages[1]*b + packages[2]*c == n:
					return 1
					#ns_passed_test.append(n)
					#print n, "passed"
	return 0

	
def test_multiple_pack_combos(packages):
	"""This function takes a tuple of tuples and tests each tuple to see what is the highest number of nuggets that cannot be exactly purchased by the packages sizes described in the tuples."""
	for n in range(1, 150):   # only search for solutions up to size 150
		## complete code here to find largest size that cannot be bought
		## when done, your answer should be bound to bestSoFar
		
		
		if is_n_solveable(n, packages):
			bestSoFar = bestSoFar + 1
		else:
			bestSoFar = 0
		
		if bestSoFar == packages[0]:
			print 'Given package sizes', packages[0], ',', packages[1], ', and', packages[2], 'the largest number of McNuggets that cannot be bought in exact quantity is:', n-packages[0]
			
for each in range(packages_to_test-1):
	#	print six_packages[each]
	test_multiple_pack_combos(six_packages[each])
Shemmerson (Self-grade: Could be better)
Submitted 4 months ago | Permalink | Time spent: 2 hours

Problem set 2

# Problem set 2.1a
# Shemmerson

# Show that it is possible to buy exactly 50, 51, 52, 53, 54, and 55 McNuggets, by finding
# solutions to the Diophantine equation.

a = 6
b = 9
c = 20

for n in range(50, 56):
    for d in range(0, n):
        for e in range(0, n):
            for f in range(0, n):
                if a*d + b*e + c*f == n:
                    print d, 'a', '+', e, 'b', '+', f, 'c', '=', n

# Substitute 

#                   for x in range (56, 66):
#                        if n + a == x:
#                           print n, '+', a, '=', x
#                       if n + b == x:
#                            print n, '+', b, '=', x

# for 

#                print d, 'a', '+', e, 'b', '+', f, 'c', '=', n

# To use given solutions to solve range (55, 66)





# Problem set 2.1b
# Shemmerson

# Once the equation is satisfied for x, x +1 ....x +5 then all further answers are 
# multiples of the same values.



# Problem set 2.3
# Shemmerson

# Shows largest number of nuggets that cannot be bought in an exact quantity. 

nugget=[]
ctr=0
n=0


for n in range (1,50): 
    test = False 
    for d in range (0,n):  
        for e in range (0,n):
            for f in range (0,n):
                if (6*d) + (9*e) + (20*f) == n:
                    test = True
                


    if test == True:
        ctr +=1
        if ctr > 5:
            print "Largest exact quantity is",nugget[-1]
    else:
        nugget.append(n)
        ctr = 0


# Problem set 2.4
# Shemmerson

# Same as above with added user control over values 

bestSoFar = []
packages = (6,9,20)
ctr = 0
n=0

for n in range(1, 100): 
    test = False
    for a in range(0,n):
        for b in range(0,n):
            for c in range(0,n):
                if (packages[0]*a) + (packages[1]*b) + (packages[2]*c) == n:
                    test = True


    if test == True:
        ctr += 1
        if ctr == 6:
            print bestSoFar[-1], "is the largest quantity not purchasable in 6,9,20 packages"
            print "............................................................"
            print "Enter your own quantities to find largest quantity not divisable:"
            bestSoFar2 = []
            ctr1 = 0
            n1=0
            x = int(raw_input ("First: "))
            y = int(raw_input ("Second: "))
            z = int(raw_input ("Third: "))
            packages = (x,y,z)
            for n1 in range(1, 50): 
                test = False
                for a in range(0,n1):
                    for b in range(0,n1):
                        for c in range(0,n1):
                            if (packages[0]*a) + (packages[1]*b) + (packages[2]*c) == n1:
                                test = True


                if test == True:
                    ctr1 += 1
                    if ctr1 == 6:
                        print bestSoFar2[-1], "is the largest exact quantity not purchasable in", + x, ",", y, "and/or", z, "packages"
                        

                else:
                    bestSoFar2.append(n1)
                    ctr1 = 0
    else:
        bestSoFar.append(n)
        ctr = 0
jillgoslinga (Self-grade: Pretty good)
Submitted 4 months ago | Permalink | Time spent: 2 hours

2.1, 2.2, 2.3, and 2.4 (Sorry, maybe I'll go back and explain my logic when I have more time / want to make my answers more complete.)

I'm excited I could get through these (2.3 and 2.4) without any hints / help from min bror this time!

#PS 2.1
#Jill Ann

Where sets of 6-McNuggets = a,
  and sets of 9-McNuggets = b,
  and sets of 20-McNuggets = c,

for:
        n = 50: a=2, b=2, c=1
        n = 51: a=4, b=3, c=0
        n = 52: a=2, b=0, c=2
        n = 53: a=1, b=3, c=1
        n = 54: a=0, b=6, c=0
        n = 55: a=1, b=1, c=2


#PS 2.2
#Jill Ann

        
Where the smallest possible number McNuggets in a single box is "a", any sequence of total (n) McNuggets n, n+1, ... until n+a allows purchase of any infinite exact numbers of McNuggets beyond the given n.
If a bunch of combinations are possible, and the difference between the smallest total transfatpacks and largest total transfatpacks in the combinations is the size of the smallest box, adding the smallest box to each subsequent combination will repeat the "flush" of possible patty combinations to infinity and beyond!


#PS 2.3
#Jill Ann

testnumber=1
countconsecutive=0
while countconsecutive<=6:
        match=False
        for samplea in range(0,testnumber):
                for sampleb in range(0,testnumber):
                        for samplec in range(0,testnumber):
                                if 6*samplea + 9*sampleb + 20*samplec == testnumber:
                                        match=True
                                        print `testnumber` + " matches with a=" + `samplea` + ", and b=" + `sampleb` + ", and c=" + `samplec`
                                        testnumber+=1
        if match == True:
                countconsecutive+=1
        if match == False:
                print `testnumber` + " is not a match"
                highestunmatched = testnumber
                testnumber +=1
                countconsecutive=0
print `highestunmatched` + " is the largest number of McNuggets that cannot be bought in exact quantity."

smallest=raw_input("How many McNuggets are in the smallest box you can buy? ")
medium=raw_input("How many McNuggets are in the 2nd smallest box you can buy? ")
largest=raw_input("How many McNuggets are in the largest box you can buy? ")


McDsizes = ( smallest, medium, largest )
a = int(McDsizes [0])
b = int(McDsizes [1])
c = int(McDsizes [2])
print a, b, c

testnumber=1
countconsecutive=0
while countconsecutive<=a:
        if testnumber < 200:
                match=False
                for samplea in range(0,testnumber):
                        for sampleb in range(0,testnumber):
                                for samplec in range(0,testnumber):
                                        if a*samplea + b*sampleb + c*samplec == testnumber:
                                                match=True
                                                #print `testnumber` + " matches with a=" + `samplea` + ", and b=" + `sampleb` + ", and c=" + `samplec`
                                                testnumber+=1
                if match == True:
                        countconsecutive+=1
                if match == False:
                        #print `testnumber` + " is not a match"
                        highestunmatched = testnumber
                        testnumber +=1
                        countconsecutive=0
print `highestunmatched` + " is the largest number of McNuggets that cannot be bought in an exact quantity."
ochikobore (Self-grade: Pretty good)
Submitted 4 months ago | Permalink | Time spent: 3 hours
#Problem Set 2
#Name: Andrew
#Time: 3-5 hours
#Collaborators: Curious Reef

def getCombination(n): #returns a dictionary of combinations for a quantity of n chicken nuggets if you can only get them in units of 6, 9, and 20.
    numOfCombos = 0
    combos = {}
    for a in range(0, n/6 + 1):
        for b in range(0, n/9 + 1):
            for c in range(0, n/20 + 1):
                if (a*6) + (b * 9) + (c * 20) == n:
                    print "a = ",a," b = ",b, " c = ",c, " n = ", n
                    numOfCombos += 1
                    combos["a"+str(numOfCombos)] = a
                    combos["b"+str(numOfCombos)] = b
                    combos["c"+str(numOfCombos)] = c
                    combos["n"+str(numOfCombos)] = n
    return combos

def middle(v1,v2,v3): ##returns the middle value for a set of three numbers
    nums = []
    smallest = min(v1,v2,v3)
    largest = max(v1,v2,v3)

    nums = [smallest, largest]

    if not v1 in nums:
        return v1
    elif not v2 in nums:
        return v2
    else:
        return v3
    
def newGetCombo(n, v1,v2,v3): ##for problem number four. built upon the first getCombination() function.
    numOfCombos = 0
    combos = {}
    for a in range(0, n/min(v1,v2,v3) + 1):
        for b in range(0, n/middle(v1,v2,v3) + 1):
            for c in range(0, n/max(v1,v2,v3) + 1):
                if (a*v1) + (b * v2) + (c * v3) == n:
                    print "a = ",a," b = ",b, " c = ",c, " n = ", n
                    numOfCombos += 1
                    combos["a"+str(numOfCombos)] = a
                    combos["b"+str(numOfCombos)] = b
                    combos["c"+str(numOfCombos)] = c
                    combos["n"+str(numOfCombos)] = n
    return combos

def problemOne():
    for n in range(50,56):
        getCombination(n)

def problemThree():
    for i in range(1,1000):
        if len(getCombination(i)) > 0:
            for j in range(1,6):
                if len(getCombination(i+j)) > 0:
                    if j == 5:
                        print "Largest number of McNuggets that cannot be bought in exact quantity: %d" % (i-1)
                        return i-1
                else:
                    i += j+1
                    break

def problemFour():
    print "Give me three McNugget sizes: " 
    v1 = input()
    v2 = input()
    v3 = input()
    for i in range(1,150):
        if len(newGetCombo(i,v1,v2,v3)) > 0:
            for j in range(1,min(v1,v2,v3)):
                if len(newGetCombo((i+j),v1,v2,v3)) > 0:
                    if j == min(v1,v2,v3)-1:
                        print "Largest number of McNuggets that cannot be bought in exact quantity: %d" % (i-1)
                        return i-1
                else:
                    i += j+1
                    break

def main():
##    problemOne()
##    problemThree()
    problemFour()

if __name__ == "__main__":
    main()
rohshall (Self-grade: Outstanding)
Submitted 7 months ago | Permalink | Time spent: 2 hours

LIMIT = 200

def is_diophantine_num(n, pack_sizes): ''' It is diophantine number if we can find non-negative numbers a, b and c such that: p1 * a + p2 * b + p3 * c = n. ''' p1, p2, p3 = pack_sizes options = range(int(n / p1) + 1) result = [(a, b, c) for a in options for b in options for c in options if p1 * a + p2 * b + p3 * c == n] #print "a,b,c for {0}: {1}".format(n, result) return bool(result)

def find_largest_nondiophantine_num(pack_sizes): smallest_possible_diophantine = pack_sizes[0] largest_nondiophantine = smallest_possible_diophantine - 1 count_diophantine = 0 for n in xrange(smallest_possible_diophantine, LIMIT): if is_diophantine_num(n, pack_sizes): count_diophantine += 1 if count_diophantine == smallest_possible_diophantine: return largest_nondiophantine else: count_diophantine = 0 largest_nondiophantine = n

if name == 'main': pack_sizes = (6, 9, 20) print "largest non diophantine num for pack sizes {0} is {1}".format( pack_sizes, find_largest_nondiophantine_num(pack_sizes))

Dith (Self-grade: Pretty good)
Submitted 9 months ago | Permalink | Time spent: 2 hours
# Problem Set 2
# Name: Hans Jacob T. Stephensen (Dith)
# Collaborators: None
# Time: XX:XX (But I've used far more than I feel I should)
# Problem ps2a.py

def nuggets(lower_limit, upper_limit):
    '''Calculate possible solutions for the Diophantine Equation of:
       "n = a*6 + b*9 + c*20" (using "exhausting enumeration")
       where n is defined by the lower and upper limit
       returns True or False if a solution is found'''
    # Checks for parameters that wouldn't yield useful results
    assert lower_limit <= upper_limit, 'the lower limit lies above the upper limit'
    assert type(lower_limit*upper_limit) == int, 'an input value is not an integer'
    assert lower_limit >= 0 and upper_limit >= 0, 'an input value is negative'
    result = False
    # Bruteforcing the three valiables by enumeration attempts, trying every possibility.
    # Dividing by 6 to get worst case scenario and to improve efficiency
    for c in range(int(upper_limit/20)+1):
        for b in range(int(upper_limit/9)+1):
            for a in range(int(upper_limit/6)+1):
                n = 6*a+9*b+20*c
                if n >= lower_limit and n <= upper_limit:
                    print 'Succes n =', n, 'With values a =', a, 'b =', b, 'c =', c
                    result = True
    print 'done'
    if result == False:
        print 'No solutions between:', lower_limit, 'and', upper_limit
        return True
    else: return False

def test_a():
    '''It't a test for the nuggets function'''
    raw_input("Testing 50 to 55")
    nuggets(50,55) #base test 1
    raw_input("Testing 56 to 65")
    nuggets(56,65) #base test 2
    raw_input("Testing 16 to 17")
    nuggets(16,17) #base test with no results
    raw_input("")
    nuggets(120,121)
    raw_input("")

test_a()

# Problem ps2b.py

def nuggets_b(nu):
    '''finds the highest value of n which lower than input value in:
    "n = 6*a + 9*b + 20*c" by use of exhausting enumeration.
    Note that values higher than 200 takes some seconds'''
    n = abs(int(nu))
    result = True
    # Checks for parameters that wouldn't yield useful results
    if type(nu) != int:
        print 'value not integer! Converting:', nu, 'to the integer of:', n
    if nu < 0:
        print 'value is not positive! Using absolute value'
    while result:
        res = 0 
        for c in range(int(n/20)+1):
            for b in range(int(n/9)+1):
                for a in range(int(n/6)+1):
                    num = 6*a+9*b+20*c
                    if num == n:
                        res += 1
                        #Edited out: print 'Solution for n =', n, 'found!'
        if res == 0:
            result = False
            print 'No solutions for n =', n, 'below the value of', nu
        n -= 1

nuggets_b(200)

def test_b():
    '''It't a test for the nuggets function'''
    raw_input("")
    nuggets_b(50) 
    raw_input("")
    nuggets_b(55.5) 
    raw_input("")
    nuggets_b(30)
    raw_input("")
    nuggets_b(-50)
    raw_input("")

test_b()
mattb (Self-grade: Outstanding)
Submitted 9 months ago | Permalink | Time spent: 3 hours

PS2

#Problem Set 2 (Part I)
#Name: mattb
#Time: 00:10
#Collaborators: Curious Reef

for n in range (50,55):
    for a in range (0, n/6 + 1):
        for b in range (0, n/9 + 1):
            for c in range (0,n/20 + 1):
                if (6 * a) + (9 * b) + (20 * c) == n:
                    print a,'a', ' + ',b,'b', '+', c,'c = ', n

# Problem Set 2 (Part II)
# Name: mattb
# Collaborators: Curious Reef
# Time: 5 minutes

#All values greater than x + 5 can be attained
#by adding multiples of 6 to the appropriate value in
#the range x, x + 1,... x + 5

# Problem Set 2 (Part III)
# Name: mattb
# Collaborators: Curious Reef
# Time: 2:00

maxn = 6
ncount = 0
n = 7
while ncount < 6:
    n += 1
    ans = False
    for a in range(0,n/6 + 1):
        for b in range(0,n/9 + 1):
            for c in range(0,n/20 + 1):
                if (6*a)+(9*b)+(20*c) == n:
                    ans = True
    if ans:
        ncount += 1
    else:
        ncount = 0
        maxn = n
        print maxn                   
print 'Largest number of McNuggets that \
cannot be bought in exact quantity: ',  maxn

# Problem Set 2 (Part IIII)
# Name: mattb
# Collaborators: Curious Reef
# Time: 20 mins

x = int(raw_input('x = '))
y = int(raw_input('y = '))
z = int(raw_input('z = '))

packages = (x,y,z)

maxn = 0
ncount = 0
n = 0
while ncount < 6 and n <200:
    n += 1
    ans = False
    for a in range(0,n/packages[0] + 1):
        for b in range(0,n/packages [1] + 1):
            for c in range(0,n/packages [2] + 1):
                if (x*a)+(y*b)+(z*c) == n:
                    ans = True
    if ans:
        ncount += 1
    else:
        ncount = 0
        maxn = n
        print maxn                   
print 'Given package sizes ', packages,' the largest \
number of McNuggets that cannot be bought in exact quantity is: ',  maxn


phaedrus (Self-grade: Pretty good)
Submitted 9 months ago | Permalink | Time spent: 2 hours

Problem Set 2

I didn't have the ps2b_template.py, so I improvised. I think this should work just as well and solve the general case.

# Problem 3

# mcdio takes an integer, num, and determines if it has a solution
# to the equation 20a + 9b + 6c = num. If it does, it returns True.
# If not, it returns nothing.
def mcdio(num):
    for i in range(0,num/20+1):
        for j in range(0,num/9+1):
	    for k in range(0,num/6+1):
	        if 20*i + 9*j + 6*k == num:
		    return True
		    print i,j,k
		    break

# mcdioSoln starts at 0 and tests every integer x to determine
# if there is a solution to 20a + 9b + 6c = x. When 5 consecutive
# x's are found such that there is a solution to the equation, it
# returns the last x such that there is no such solution.
def mcdioSoln():
    num = 0
    cons = 0
    bestFound = 0
    while cons < 6:
        num += 1
        if mcdio(num) == True:
	    cons += 1
	else:
	    cons = 0
	    bestFound = num
    return bestFound



# Problem 4

# gen_mcdio will be called by gen_mcdio_search to determine if the
# current number being tested by gen_mcdio_search has a solution
# for the given a,b,c.
def gen_mcdio(a,b,c,n):
    for i in range(0,n/c+1):
        for j in range(0,n/b+1):
	    for k in range(0,n/a+1):
	        if c*i + b*j + a*k == n:
	            return True

# gen_mcdio_search iterates through the positive integers less than
# 200 and calls gen_mcdio to test if a number has a solution.
def gen_mcdio_search(num1,num2,num3):
    cons = 0
    bestFound = 0
    while cons < 6:
        for n in range(0,200):
	    n += 1
            if gen_mcdio(num1,num2,num3,n):
	        cons += 1
	    else:
	        cons = 0
		bestFound = n
    return bestFound

# Example:
gen_mcdio_search(5,8,10)  # returns 27
gio (Self-grade: Pretty good)
Submitted 10 months ago | Permalink | Time spent: 3 hours
  4 # Problem Set 2
  5 # Problem #1
  6 # Gio
  7 #
  8 def mcnugget(n):
  9     a = 6
 10     b = 9
 11     c = 20
 12     for x in range(0, n):
 13         for y in range(0, n):
 14             for z in range(0, n):
 15                     if a*x + b*y + c*z == n:
 16                         #print x, y, z
 17                         return True
 18     return False
 19 
 20 #print mcnugget(50)
 21 
 22 
 23 #Problem 3
 24 def largest_mcnugget():
 25     n = 1
 26     while n < 100:
 27         if not mcnugget(n):
 28             new_n = n
 29         n += 1
 30     print 'Largest number of McNuggets that cannot be bought in exact quantity: %d' % new_n
 31 
 32 largest_mcnugget()

#########################################

 13 # Problem Set 2
 14 # Problem 4
 15 # Gio
 16 packages = (5, 11, 19)
 17 
 18 def mcnuggets(n):
 19     a = packages[0]
 20     b = packages[1]
 21     c = packages[2]
 22     for x in range(0, n):
 23         for y in range(0, n):
 24             for z in range(0, n):
 25                 if a*x + b*y + c*z == n:
 26                    # print x, y, z
 27                     return True
 28     return False
 29 
 30 #print mcnuggets(55)
 31 
 32 # Problem 3
 33 def largest_mcnuggets():
 34    # bestSoFar = 0
 35     for n in range(1, 200):
 36         if not mcnuggets(n):
 37             bestSoFar = n
 38     print 'Given package sizes %r, %r, and %r, the largest number of McNuggets\nThat cannot be bought in exact quantity is: %r' % (packages[0], packages[1], packages[2], bestSoFar)
 39 
 40 largest_mcnuggets()
nick18 (Self-grade: Outstanding)
Submitted 10 months ago | Permalink | Time spent: 10 minutes

MIT Lesson 3: Assignment 1

#Problem Set 2
#Name: Nick
#Time: 00:10
#Collaborators: None

#Problem 1
region = range(50, 55)

for a in range (0, 20):
        for b in range(0,20):
                for c in range(0,20):
                        k = 6 * a + 9 * b + 20 * c;
                        if k in region:
                                print("{0:2}*6 + {1}*9 + {2}*20 = {3}".format(a,b,c,k));

#       2*6 + 2*9 + 1*20 = 50
#       5*6 + 1*9 + 0*20 = 51
#       2*6 + 0*9 + 2*20 = 52
#       1*6 + 3*9 + 1*20 = 53   
#       9*6 + 0*9 + 0*20 = 54
#       1*6 + 1*9 + 2*20 = 55

#Problem 2
"""
        Theorem is true because when we had all x, x+1,..., x+5 all next steps will repeat.
        For example if we has 54 nugets we can add 6 and get 60 or 51 + 6 =57.
        This works for any x, ...,  x+5 values
"""

#Problem 3
def can_buy(n, ax, bx, cx):
        for a in range(0,20):
                for b in range(0,20):
                        for c in range(0,20):
                                k = ax * a + bx * b + cx * c
                                if k == n:
                                        return True
        return False

def solve(a,b,c):
        count = 0
        for n in range(1,200):
                if not can_buy(n,a,b,c):
                        ans = n
                        count = 0
                else:   count += 1
                if count == 6:  break
        print("Given package sizes <{0}>, <{1}>, <{2}>, the largest number of McNuggets that cannot be bought in exact quantity is: {3}".format(a,b,c,ans))


solve(6,9,20)

#Problem 4
solve(10,14,15)
meanmuggin (Self-grade: Pretty good)
Submitted 10 months ago | Permalink | Time spent: 5 hours
##x = input('Please enter number of nuggets you would like ')



packages = input('Input list of package sizes [a,b,c] ')

vec_len = len(packages)

abc_vars_limit = range(1,vec_len+1)


x = 0
limit = 100
num_n_log = []

while x < limit:


    m = 0
    while m < vec_len:
        abc_vars_limit[m] = x/packages[m]
        m += 1 

    ##print abc_vars_limit

    a = range(0,abc_vars_limit[0]+1)
    b = range(0,abc_vars_limit[1]+1)
    c = range(0,abc_vars_limit[2]+1)

    ##print a
    ##print b
    ##print c

    a2 = []
    b2 = []
    c2 = []
    abc = []

    for i in a:
        for j in b:
            for k in c:         
                if x == packages[0]*a[i]+packages[1]*b[j]+packages[2]*c[k]:
                  a2 = a2 + [i]
                  b2 = b2 + [j]
                  c2 = c2 + [k]

    if a2 == [] and b2 == [] and c2 == []:
    
     num_n_log = num_n_log + [x]
##    print a2
##    print b2
##    print c2
##    print num_n_log
    x += 1
## 
##
##
##
print 'These numbers cannot be bought in exact quantity'
print num_n_log
 
s = 'Given package sizes ' + repr(packages[0])+ ' ' + repr(packages[1]) + ' and ' + repr(packages[2]) + ' the largest number of McNuggets that cannot be bought in exact quantity is: ' + repr(num_n_log[-1])
print s 
Vidyaranya (Self-grade: Pretty good)
Submitted 10 months ago | Permalink | Time spent: 5 hours
##problem2
##since we can buy nuggets in x, x +1, x+5,
##in packs of 6,9,20. Which means that any large enough of ##amounts  of nuggets can be bought with these sizes of ##packs  as long as the first six continuous amount of ##nuggets set are established, as the 7th nugget is just ##6more than the first nugget and the 8th is 6 more than the ##2 nugget of that set
##and so on..... 









##PROBLEM 3




notreachable=[]
counter=0
n=0
for n in range (6,100):
    ans = False
    for s in range (0,n+1):
        for m in range (0,n+1):
            for l in range (0,n+1):
                if (6*s) + (9*m) + (20*l) == n:
                    ans = True
                


    if ans:
        counter +=1
        if counter == 6:
            print ("Largest number of McNuggets that cannot be bought in exact quantity:  ",notreachable[-1])
    else:
        notreachable.append(n)
        counter = 0




##problem 4
package = (13,17,19)
notreachable = 0
counter = 0
n = 0
for n in range (n, 200):
    ans = False
    for s in range (0, n+1):
        for m in range (0, n+1):
            for l in range (0,n+1):
                if ((s*package[0]) + (m*package[1]) + (l*package[2]) == n):
                    ans = True    
                
                    
    


    if ans:
        counter+=1
        if package[0] == counter:
            break;
    else:
        counter = 0
        notreachable = n
print ("Given that sizes %d, %d, and %d, the largest number of McNuggets that cannot be bought in exact quantity is: %d" % (package[0], package[1], package[2], notreachable))
tuckertuck (Self-grade: Pretty good)
Submitted 11 months ago | Permalink | Time spent: 4 hours

This was hard for me to figure out until I watched the fourth lecture. I still don't think I understand exactly how I made it work, but I'm pretty sure it works, heh.

##6a + 9b + 20c = n
##
##n | a  b  c		n | a  b  c		n | a  b  c
##——————————————————————————————————————————————-------------
##50  5  0  1		56  6  0  1		62  7  0  1
##51  7  1  0		57  8  1  0		63  9  1  0
##52  2  0  2		58  3  0  2		64  4  0  2
##53  4  1  1		59  5  1  1		65  6  1  1
##54  9  0  0		60  10 0  0		
##55  1  1  2		61  2  1  2		
##
##This theorem is true because when six consecutive numbers are solvable every number afterwards is solvable by adding another six to the previous totals.


# Problem Set 2 (Problem 3)
# tuckertuck
# time = 4:00

BestSoFar = 0
packages = (9,6,20)
count = 0

def BruteForceNuggets(n,(x,y,z)):
    for a in range(0, n + 1):
        for b in range(0, n - (a * x) + 1):
            c = (n - (b * y) - (a * x)) / z
            if c >= 0:
                #print (x*a),'+',(y*b),'+',(z*c),'=',n
                if (a * x) + (b * y) + (c * z) == n:
                    return True
    return False

for n in range(1, 200):
    if not BruteForceNuggets(n,packages):
        BestSoFar = n
        print BestSoFar,
        count = 0
    count += 1
    print count
    sortPackage = sorted(packages)
    if count > sortPackage[0]:
        break
print 'Largest number of McNuggets that cannot be bought in exact quantity:',BestSoFar



# Problem Set 2 (Problem 4)
# tuckertuck


bestSoFar = 0     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
packages = (13,16,25)   # variable that contains package sizes

count = 0

def BruteForceNuggets(n,(x,y,z)):
    for a in range(0, n + 1):
        for b in range(0, n - (a * x) + 1):
            c = (n - (b * y) - (a * x)) / z
            if c >= 0:
                #print (x*a),'+',(y*b),'+',(z*c),'=',n
                if (a * x) + (b * y) + (c * z) == n:
                    return True
    return False

    
for n in range(1, 200):
    if not BruteForceNuggets(n,packages):
        BestSoFar = n
        #print BestSoFar
        count = 0
    count += 1
    #print count,
    sortPackage = sorted(packages)
    if count > sortPackage[0]:
        break
print "Given package sizes", packages[0], packages[1], "and", packages[2], "the largest number of McNuggets that cannot be bought in exact quantity is:", BestSoFar
xwb1989 (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 5 hours
def solve(n,a,b,c):
    for x in range(0,int(n/a)+1):
        for y in range(0,int(n/b)+1):
            for z in range(0,int(n/c)+1):
                if n==a*x + b*y + c*z:
                    return n
    return False
def item(a,b,c):
    n = 6
    while True:
        if solve(n,a,b,c) and solve(n+1,a,b,c)\
           and solve(n+2,a,b,c) and solve(n+3,a,b,c)\
           and solve(n+4,a,b,c) and solve(n+5,a,b,c):
            print(n-1,'is the last sum of Mcnuggets that can\'t be bought.')
            return
        n+=1
mjcuva (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 2 hours

ps2

##Problem 1
##
##50 = 2,2,1
##51 = 1,5,0
##52 = 2,0,2
##53 = 1,3,1
##54 = 0,6,0
##55 = 1,1,2
##
##Problem 2
##
##Since it is possible to buy x,x+1...,x+5 McNuggets,
##you can add the lowest choice 6 to the total and still
##have a number that is able to be purchased with the
##combination of 6, 9,or 20 McNuggets.
##
##Problem 3

nuggets = (6,9,20)    
best_so_far = 0       
counter = 0           
for loop_counter in range(1,200):    
    checker = False
    for a in range(0,loop_counter/nuggets[0] +1):
        for b in range(0,loop_counter/nuggets[1] + 1):
            for c in range(0,loop_counter/nuggets[2] + 1):
                solution = a*nuggets[0]+b*nuggets[1]+c*nuggets[2]
                if solution == loop_counter:
                    counter = counter + 1
                    checker = True
                if checker == True:
                    break
            if checker == True:
                break
        if checker == True:
            break
    if checker == False:
        counter = 0
        best_so_far = loop_counter
print 'Largest number of McNuggets that cannot be bought in an exact quantity is',best_so_far

##Problem 4

nuggets = (6,9,20)    
best_so_far = 0       
counter = 0
for loop_counter in range(1,200):
    checker = False
    for a in range(0,loop_counter/nuggets[0] +1):
        for b in range(0,loop_counter/nuggets[1] + 1):
            for c in range(0,loop_counter/nuggets[2] + 1):
                solution = a*nuggets[0]+b*nuggets[1]+c*nuggets[2]
                if solution == loop_counter:
                    counter = counter + 1
                    checker = True
                if checker == True:
                    break
            if checker == True:
                break
        if checker == True:
            break
    if checker == False:
        counter = 0
        best_so_far = loop_counter
print 'Given package sizes',nuggets[0],',',nuggets[1],', and',nuggets[2],' the largest number of McNuggets that cannot be bought in exact quantity is',best_so_far
dmoyer2 (Self-grade: Pretty good)
Submitted 1 year ago | Permalink | Time spent: 18 minutes
# Problem Set 2  (Lesson 2, assignment 1)

import math

a=0
b=0
c=0
n=50


for n in range (50,56):
    for a in range (0, n/6 +1):
        for b in range (0,n/9 + 1):
            for c in range (0, n/20 +1):
                if (((6*a) + (9*b) + (20*c)) == n):
                    print 'ok a,b,c ' , a,b,c
            c=+1
        b=+1
    a=+1
n=+1
eko (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 1 minute
#problem 3 -mcnuggets


count=0

n=1
exact=0

while count<6 :
  
    for a in range (0,9) :
        for b in range (0,6) :
            for c in range (0,3):
                if 6*a + 9*b + 20*c == n :
                    exact=1
    if exact == 1 :
        count +=1
    else :
        largest=n
        count=0
    n+=1
    exact=0          

print "Largest number of McNuggets that cannot be bought in exact quantity: "largest

----------------------------------------------------

#problem 4 -mcnuggets



x=(int(raw_input("small package size: ")))
y=(int(raw_input("medium package size: ")))
z=(int(raw_input("large package size: ")))

up=(int(raw_input("up to what number to check?")))

packages=(x,y,z)
count=0
n=1
bestSoFar=0
exact=0
flag=0


while count<x :
  for n in range (1,up):
    for a in range (0,up/x+x) :
        for b in range (0,up/y+y) :
            for c in range (0,up/z+z):
                if x*a + y*b + z*c == n :
                    exact=1
    if exact == 1 :
        count +=1
    else :
        bestSoFar=n
        count=0
    n+=1
    exact=0          
  if count<x :
      flag=1
      print "There is no number up to ",up ,"which cannot be bought"
      break

if flag!=1:
    print "Given package sizes ",x ,y, z
    print "the largest number of McNuggets that cannot be bought"
    print "in exact quantity is: ",bestSoFar
fell (Self-grade: Pretty good)
Submitted 1 year ago | Permalink | Time spent: 3 days

0

0
jimmy (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 1 minute
## Problem Set 2
## Name: Jimmy
## Time: forever

##Part A


##McNuggets Package (6, 9, 20)
##
##50 = 6(2) + 9(2) + 20(1)
##
##51 = 6(7) + 9(1) + 20(0)
##
##52 = 6(2) + 9(0) + 20(2)
##
##53 = 6(1) + 9(3) + 20(1)
##
##54 = 6(3) + 9(4) + 20(0)
##
##55 = 6(1) + 9(1) + 20(2)
##
##56 = 6(3) + 9(2) + 20(1)
##
##57 = 6(8) + 9(1) + 20(0)
##
##58 = 6(3) + 9(0) + 20(2)
##
##59 = 6(2) + 9(3) + 20(1)
##
##60 = 6(1) + 9(6) + 20(0)
##
##61 = 6(2) + 9(1) + 20(2)
##
##62 = 6(4) + 9(2) + 20(1)
##
##63 = 6(0) + 9(7) + 20(0)
##
##64 = 6(1) + 9(2) + 20(2)
##
##65 = 6(3) + 9(3) + 20(1)


##Part B

## This theorem is true because any number of McNuggets >= x can be expressed
##as a linear combination 6a+9b+20c if x+1, x+2, x+3, x+4 and x+5 all have a
##solution

##Part C

nuggets = []
counter = 0
n = 0
for n in range(1,1000):
    answer = False
    for a in range(0,n/6+1):
        for b in range(0,n/9+1):
            for c in range(0,n/20+1):
                if (6*a)+(9*b)+(20*c) == n:
                    answer = True
    if answer == True:
        counter = counter + 1
        if counter == 10:
            print 'the largest impossible quantity of nuggets is:', nuggets[-1]
    else:
        nuggets.append(n)
        counter = 0

##Part D

packs=(6, 9, 20)
nuggets=0

for n in range(1, 200):
    answer=False
    for a in range(0,n/6+1):
        for b in range(0,n/9+1):
            for c in range(0,n/20+1):
                if (packs[0]*a)+(packs[1]*b)+(packs[2]*c)==n:
                    answer=True
    if (answer==False):
        if (n>nuggets): nuggets=n
print "Given package sizes "+str(packs[0])+ ', ' +str(packs[1])+  ', and ' +str(packs[2])+", the largest number of McNuggets that cannot be bought in exact quantity is: "+str(nuggets)

Comments:

mitswan
12 months ago

Why do we have to check if (n>nuggets) Cant the code be like this: if(answer==False):nuggets=n Please help me understand why we need that check. Thanks

Sign up or log in to comment

TheHedge (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 1 minute
# Problem Set 2
# Name: TheHedge
# Collaborators: 0
# Time: 05:00:00

# PROBLEM 1
packages = (6,9,20)

def mcComboPossible(n):
    Possible = False
    for a in range (0,n):
        for b in range (0,n):
            for c in range (0,n):
                if (packages[0]*a) + (packages[1]*b) + (packages[2]*c) ==n:
                    Possible = True
                c += 1
            b += 1
        a += 1
    return Possible

def mcCombo(n):
    for a in range (0,n):
        for b in range (0,n):
            for c in range (0,n):
                if (packages[0]*a) + (packages[1]*b) + (packages[2]*c) ==n:
                    print 'to get' ,n, 'nuggets, you could buy ' ,a, 'x ', packages[0],' nuggets' ,b, 'x', packages[1],' nuggets, and' ,c, 'x ',packages[2],' nuggets'
                c += 1
            b += 1
        a += 1

numNuggets = int(raw_input('How many nuggets would you like? \n'))

if mcComboPossible(numNuggets) == False:
    print 'Sorry, that is not possible!'
else:
    mcCombo(numNuggets)

# PROBLEM 3
nCount =0

for a in range (6,100):
    if mcComboPossible(a) == True:
        nCount +=1
        if nCount == 6:
            print 'The largest number of McNuggets that cannot be bought in exact quantity is' ,a-6,' \n'  
    else:
        nCount = 0
        
# PROBLEM 4
limit = 50

def getMcCombos(limit,x,y,z):
    Possible = False
    for a in range (0,limit):
        for b in range (0,limit):
            for c in range (0,limit):
                if (packages[0]*a) + (packages[1]*b) + (packages[2]*c) ==limit:
                    Possible = True
                c += 1
            b += 1
        a += 1
    return Possible


while getMcCombos(limit,packages[0],packages[1],packages[2]) == True:
    limit -=1
    getMcCombos(limit,packages[0],packages[1],packages[2])
print 'Given package sizes ', packages[0],',', packages[1], 'and', packages[2],'the largest number of nuggets that connot be bought in the exact quantity is', limit,
    
mercutio22 (Self-grade: Pretty good)
Submitted 1 year ago | Permalink | Time spent: 5 days
#####################PS2a.py############
#!/usr/bin/env python
#encoding=utf-8

#6a+9b+20c=n n=50 to 55
def solve(n):
    """finds one solution for the dioohantine equation 6a+9b+20c=n"""
    for a in range (0,n/6+1):#upper limit is set so you don't extrapolate the upper value of n+5 when multiplying a, b, or c.
            for b in range(0,n/9+1):#same here
                for c in range (0,n/20+1):#same here
                    randomcombo = 6*a + 9*b + 20*c
                    if n == randomcombo: 
                        #print "Solução para n = " + str(n) + ":", "("+str(a)+","+str(b)+","+str(c)+")"
                        return [randomcombo,a,b,c]
                    else:
                        pass
    return False
                        
def FindSolutions(x):
    """tries to find 5 consecutive solutions for the McNuggets problem, this is for problem 1 of problem set 2 when x = 50"""
    solutionslist = []
    L = range(x,x+6)
    for numberNuggets in L: #try combinations of a, b and c till one solution is found
        if solve(numberNuggets) != False:       
            solutionslist.append(solve(numberNuggets))    
    return solutionslist


#def verify(x):
#    """checks if there exists solutions for all elements in range x,x+5"""
#    x=raw_input("input x: ")
#    FindSolutions(x)
#    if len(solutionslist) < 5:
#        return False 
#    else:   
#        return True
#see if verify(x) is true then there exists solutions for every number > x+5 because we can write any of them in terms of previous solution plus packages of 6, 9 and 20.

## Agora para a segunda parte do problema:

def nope():
    """Encontra o maior número de McNuggets que não pode ser comprado em quantidade exata"""
    unbuyable=[]
    x = 0
    while len(FindSolutions(x)) < 6:#we know from the theorem that once 6 consecutive solutions are found, there are endless solutions.
        x+=1
        if solve(x) == False:
            unbuyable.append(x)#saves an unbuyable value everytime one is found.           
    else:
        print "Largest number of McNuggets that cannot be bought in exact quantity:", unbuyable[-1]
        
print solve(52)
nope()
#print len(FindSolutions(50))

######ps2b.py##############################
#!/usr/bin/env python
#encoding=utf-8


###
### template of code for Problem 4 of Problem Set 2, Fall 2008
####x.a+y.b+z.c=n 

#bestSoFar = 0     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
packages = (9,12,23)   # variable that contains package sizes
maxn=150
#for n in range(1, 150):   # only search for solutions up to size 150
    ## complete code here to find largest size that cannot be bought
    ## when done, your answer should be bound to bestSoFar

def solve(n):
    """finds one solution for the dioohantine equation 6a+9b+20c=n"""
    for a in range (0,n/packages[0]+1):#upper limit is set so you don't extrapolate the upper value of n+5 when multiplying a, b, or c.
            for b in range(0,n/packages[1]+1):#same here
                for c in range (0,n/packages[2]+1):#same here
                    randomcombo = packages[0]*a + packages[1]*b + packages[2]*c
                    if n == randomcombo: 
                        #print "Solução para n = " + str(n) + ":", "("+str(a)+","+str(b)+","+str(c)+")"
                        return [randomcombo,a,b,c]
                    else:
                        pass
    #print 'There is no solution' 
    return False

def FindSolutions(x):
    """tries to find 5 consecutive solutions for the McNuggets problem, this is for problem 1 of problem set 2 when x = 50"""
    solutionslist = []
    L = range(x,x+packages[0])
    for numberNuggets in L: #try combinations of a, b and c till one solution is found
        if solve(numberNuggets) != False:       
            solutionslist.append(solve(numberNuggets))    
    return solutionslist


def nope():
    """Encontra o maior número de McNuggets que não pode ser comprado em quantidade exata"""
    unbuyable=[]
    x = 0
    while len(FindSolutions(x)) < packages[0]:#we know from the theorem that once 6 consecutive solutions are found, there are endless solutions.
        x+=1
        if solve(x) == False:
            unbuyable.append(x)#saves an unbuyable value everytime one is found.
        elif x > maxn:
            print 'não existe n<', maxn, 'que funciona nessa esquação.'
            return            
    else:
        print "Largest number of McNuggets that cannot be bought in exact quantity:", unbuyable[-1]

nope()
fredgust (Self-grade: Pretty good)
Submitted 1 year ago | Permalink | Time spent: 1 hour

There is some optimization to do in this solution

# Problem Set 2
# Name: Fredrik Gustafsson
# Python version: 3.2
# Time: 1:00


##
## Problem 2a
##

def mcnuggets(n, p):
    
    x = 0
    y = 0
    z = 0
    count = 0

    while x*p[0]+y*p[1]+z*p[2] <= n:
        while x*p[0]+y*p[1]+z*p[2] <= n:
            while x*p[0]+y*p[1]+z*p[2] <= n:
                if x*p[0]+y*p[1]+z*p[2] == n:
                    return ("Solution found")
                    count += 1
                x += 1
            x = 0
            y += 1
        y = 0
        z += 1
    return (count)

for i in range (50, 56):
    print ("Nr of solutions to the equation: 6x + 9y + 20z =", i, "is:", mcnuggets(i, (6, 9, 20)))


##
## Problem 2b: Any number of McNuggets >= x can be expressed as a linear combination
## 6a+9b+20c if x+1, x+2, ..., x+5 all have a solution
##


##
## Problem 2c
##

def serch(p):

    count = 0
    x = 0

    while count <= (p[0]-1):
        if  x > 200:
            return ("No solution found for largest number of McNuggets that cannot be bought in exact quantity whithin the range 0 - 200")
        if mcnuggets(x, (p[0], p[1], p[2])) != 0:
            count += 1
            x += 1
        else:
            count = 0
            x += 1

    return(x-(p[0]+1))


##
## Problem 2d
##

a = int(input("Pleas input nr of McNuggets in smallest package: "))
b = int(input("Pleas input nr of McNuggets in middle package: "))
c = int(input("Pleas input nr of McNuggets in largest package: "))

packages = (a, b, c)        # variable that contains package sizes
bestSoFar = serch(packages)     # variable that keeps track of largest number
                                # of McNuggets that cannot be bought in exact quantity
print (bestSoFar)
apoo (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 1 hour
#===================== Problem 1 ==========================
def nuggetsFound(n):
    """
    Returns a dictionary contaning Key: number of Nuggets Value: the
    packages
    """
    dic = {}
    for i in range(0,n+1):
        for j in range(0,n+1):
            for k in range(0,n+1):
                if (6*i) + (9*j)+ (20*k) == n:
                    if n in dic:
                        dic[n].append((i,j,k))
                    else:
                        dic[n] = [(i,j,k)] 
    return dic

def displayNuggestsFound(n):
    """
    Gets a input (number of Nuggets) and pass it as an argument to 
    nuggetsFound(). Finally prints the output from nuggetsFound
    """
    nMcNuggets = n # n = 50,51,52,53,54,54
    dicNuggets = nuggetsFound(nMcNuggets)
    for nuggets,numbers in dicNuggets.iteritems():
       if type(numbers) == type([]):
            for number in numbers:
                 print 'Number of McNuggets:',nuggets,'The set:', number
       else:
                 print 'Number of McNuggets:',nuggets,'The set:', number

#===================== Problem 2 ===================
##### The theorem is true becasue any set after x, x+5 is a multiplay of 6.
##### Because 50 + 6 = 56 (a new set with only 6 added), 51 + 6 = 57 (new set with adding 6) and so on so on. 
##### Therefore we can create a new set with the combination of 6, 9 and 12!

#==================== Problem 3 ====================
def numNuggetsNotExact(n):
    """
    """
    Found = False
    notExact = 0
    for i in range(0,n):
        for j in range(0,n):
            for k in range(0,n):
                if (6*i) + (9*j)+ (20*k) == n:
                    Found = True
    return Found  


def displaynumNuggetsNotExact():
    nuggetsNotPurchased = 1 
    n = 2
    counter = 1
    while n < 50:
        n = n +1 
        if not numNuggetsNotExact(n):
            nuggetsNotPurchased = n
            counter = 0
        else:
            counter = counter + 1
        if counter == 6:
            return "Largest number of McNuggets that cannot be bought in exact quantity: %d" % nuggetsNotPurchased

# ================== Problem 4 =========================


def nNumberNuggetsNotExact(x,y,z):
    bestSoFar = 0
    packages = (x,y,z)
    counter = 0
    for n in range(1,200):
        found = False
        for i in range(0 ,200):
            for j in range(0,200):
                for k in range(0,200):
                    if (i * packages[0]) + (j * packages[1])+ (k * packages[2]) == n:
                        found = True
        if found:
            counter = counter + 1
        if not found: 
            bestSoFar = n
            counter = 0
        if counter == packages[0]:
            print "Given package sizes %d, %d and %d, the largest number of McNuggets that cannot be bought in exact quantity is %d" % (packages[0],packages[1],packages[2],bestSoFar) 
vbakhtyr (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 1 minute
# Prob 1

def combos(n): 
   for a in range (0,n): 
      for b in range (0,n):
         for c in range (0,n):
            if (6*a) + (9*b) + (20*c) == n:
               print a, "x6pcks + ",b,"x9pcks+ ",c, "x20pcks = ", n, "nuggets."
            c = c + 1
         b = b + 1
      a = a + 1
      
combos (12)

# Prob 2
#Magic

# Prob 3

answer=[]
n_counter=0
n=0
for n in range(1, 200):
    ans=False
    for a in range(0,n/6+1):
        for b in range(0,n/9+1):
            for c in range(0,n/20+1):
                if (6*a)+(9*b)+(20*c)==n:
                    ans = True
    if ans:
        n_counter+=1
        if n_counter==6:
            print 'the largest impossible quantity of nuggets is: ',  answer[-1]
    else:
        answer.append(n)
        n_counter = 0


# Prob 4
packages=(6, 9, 20)
answer=0

for n in range(1, 200):
    ans=False
    for a in range(0,n/6+1):
        for b in range(0,n/9+1):
            for c in range(0,n/20+1):
                if (packages[0]*a)+(packages[1]*b)+(packages[2]*c)==n:
                    ans=True
    if (ans==False):
        if (n>answer): answer=n
print "Given package sizes "+str(packages[0])+ ', ' +str(packages[1])+  ', and ' +str(packages[2])+", the largest number of McNuggets that cannot be bought in exact quantity is: "+str(answer)

Comments:

mitswan
12 months ago

The one thing I don't get is... why did you check for (n>answer) Can't it be: if (ans==False):answer=n I think I'm unable to imagine a case where n<=answer.

Sign up or log in to comment

ariel0 (Self-grade: Pretty good)
Submitted 1 year ago | Permalink | Time spent: 35 minutes

sorry if my English is not very good

# Problem 1
#
# Name: Ariel Mamani (ariel0)    
# Collaborators: 
# Time: 9:31
#

#funcion que devuelve el valor de la ecuacion
#6a+9b+20c
def ecuacion(a,b,c):
    return 6*a+9*b+20*c


#funcion que calcula las combinaciones de McNuggets
#para una cantidad dada
def comprar(cantidad):
    #3 bucles que iteran los valores de a,b y c en:
    #6a+9b+20c
    a=0
    while a<=cantidad:
        b=0
        if(ecuacion(a,b,0)>cantidad): break
        while b<=cantidad:
            c=0
            if(ecuacion(a,b,c)>cantidad): break
            while c<=cantidad:
                if(ecuacion(a,b,c)==cantidad):
                    print "(a="+str(a)+",b="+str(b)+",c="+str(c)+") , 6*"+str(a)+"+9*"+str(b)+"+20*"+str(c)+"="+str(cantidad)
                elif(ecuacion(a,b,c)>cantidad): break
                c=c+1
            b=b+1
        a=a+1

#probar desde 50 -> 65
for i in range(140,150):
    print "Para comprar "+str(i)+" McNuggets:"
    comprar(i)


#Problem 2
#
#El teorema es cierto ya que si es posible comprar x, x+1,…, x+5 McNuggets 
#y se tiene paquetes de 6, 9 y 20, todos los siguientes valores se pueden 
#comprar añadiendo a cada valor en el rango de x, x+1,…, x+5 un multiplo de 6.
#Es decir, si x+y es cualquier valor mayor a x+5:
#x+y=6*i donde i es cualquier valor de x -> x+5.

#The theorem is true because if you can buy x, x +1, ..., x +5 McNuggets
#and we have packages of 6, 9 and 20, all of the following values can be
#buy adding to each value in the range of x, x +1, ..., x +5 a multiple of 6.
#That is, if x + y is any value greater than x + 5:
#	x+y=6*i where i is any value of x -> x+5.


# Problem 3
# 
# Name: Ariel Mamani (ariel0)    
# Collaborators: 
# Time: 10:31
#

#funcion que devuelve el valor de la ecuacion
#6a+9b+20c
def ecuacion(a,b,c):
    return 6*a+9*b+20*c


#funcion que devuelve True si existe una combinacion para comprar la cantidad McNuggets
#devuelve False si no es posible comprar la cantidad dada
def comprar(cantidad):
    #3 bucles que iteran los valores de a,b y c en:
    #6a+9b+20c
    a=0
    while a<=cantidad:
        b=0
        if(ecuacion(a,b,0)>cantidad): break
        while b<=cantidad:
            c=0
            if(ecuacion(a,b,c)>cantidad): break
            while c<=cantidad:
                if(ecuacion(a,b,c)==cantidad):
                    return True
                elif(ecuacion(a,b,c)>cantidad): break
                c=c+1
            b=b+1
        a=a+1
    return False

#probar desde 49 -> 0
#como con el Teorema anterior se probo que se puede comprar McNuggets desde 50 en
#adelante, no tiene sentido comprobar desde 50 en adelante
#si probamos desde 49 hacia abajo, la primera vez que obtengamos una cantidad que
#no puede ser comprada, esta sera la mayor.
i=49
while(i>=0):
    if(comprar(i)==False):
        print "Largest number of McNuggets that cannot be bought in exact quantity: "+str(i)
        break
    i=i-1



# Problem 4
#
# Name: Ariel Mamani (ariel0)  
# Collaborators: 
# Time: 10:31
#
###
### template of code for Problem 4 of Problem Set 2, Fall 2008
###

bestSoFar = 0     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
packages = (6,9,20)   # variable that contains package sizes

for n in range(1, 150):   # only search for solutions up to size 150
    ## complete code here to find largest size that cannot be bought
    ## when done, your answer should be bound to bestSoFar

    posible=False
    a=0
    while a<=n:
        b=0
        c=0
        if(packages[0]*a+packages[1]*b+packages[2]*c>n): break
        while b<=n:
            c=0
            if(packages[0]*a+packages[1]*b+packages[2]*c>n): break
            while c<=n:
                if(packages[0]*a+packages[1]*b+packages[2]*c==n):
                    posible=True
                elif(packages[0]*a+packages[1]*b+packages[2]*c>n): break
                c=c+1
            b=b+1
        a=a+1
    if(posible==False):
        if(n>bestSoFar):bestSoFar=n

print "Given package sizes "+str(packages[0])+", "+str(packages[1])+", and "+str(packages[2])+", the largest number of McNuggets that cannot be bought in exact quantity is: "+str(bestSoFar)
dacorest (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 1 minute
#Name: Waz
# Problem set 2

# _____________Part 1_______
#to show the combos, let's create a function to do so
def showcombos(noofng):
   for a in range (0,noofng+1):
      for b in range (0,noofng+1):
         for c in range (0,noofng+1):
            if (6*a) + (9*b) + (20*c) == noofng:
               print a, "x6pcks + ",b,"x9pcks+ ",c, "x20pcks = ", noofng, "nuggets."
            c = c + 1
         b = b + 1
      a = a + 1
#let's show the results
print "\n Combos for 50 nuggets"
showcombos (50)
print "\n Combos for 51 nuggets"
showcombos (51)
print "\n Combos for 52 nuggets"
showcombos (52)
print "\n Combos for 53 nuggets"
showcombos (53)
print "\n Combos for 54 nuggets"
showcombos (54)
print "\n Combos for 55 nuggets"
showcombos (55)


____________Part 2_______

print "\n The reason that every number greater than x will generate a combo is \n because every number higher than x+5 equals to a number between x and x+5 plus \n a multiple of 6. That multiple will only augment 'a' but we will still have a combo"

___________Part3___________


def showcombos(noofng): #noofng = number of nuggets
   for a in range (0,noofng+1):
      for b in range (0,noofng+1):
         for c in range (0,noofng+1):
            if (6*a) + (9*b) + (20*c) == noofng:
               Hascombo = True
               return Hascombo
          
strt=50  #we are starting from 50 because we know anything >50 will have a combo.
while showcombos(strt)<> None:
    strt = strt - 1
    showcombos (strt)
print "Largest number of McNuggets that cannot be bought in exact quantity: ", strt

#------------Generalized version--------------------
def showcombos(noofng,x,y,z):  
   for a in range (0,noofng+1):
      for b in range (0,noofng+1):
         for c in range (0,noofng+1):
            if (x*a) + (y*b) + (z*c) == noofng:
               Hascombo = True
               return Hascombo
          
def findbiggest (strt, x,y,z): #x,y,z are the sizes of the packages & strt= where to start counting down
   while showcombos(strt,x,y,z)<> None:
       print strt, "has combos"
       strt -= 1
       showcombos (strt,x,y,z)
   print strt, " is the biggest number of nuggets that you can't\nhave the exact amount with that combo."

_________Part 4________________


def showcombos(noofng,x,y,z):  
   for a in range (0,noofng+1):
      for b in range (0,noofng+1):
         for c in range (0,noofng+1):
            if (x*a) + (y*b) + (z*c) == noofng:
               Hascombo = True
               return Hascombo
          
def findbiggestu200 (x,y,z): #x,y,z are the sizes of the packages 
   strt =200
   while showcombos(strt,x,y,z)<> None:
       strt -= 1
       showcombos (strt,x,y,z)
   print "Given package sizes ",x,",", y, "and ",z," the largest number of McNuggets that cannot be bought in exact quantity is: ", strt
baggedlunch (Self-grade: Could be better)
Submitted 1 year ago | Permalink | Time spent: 1 hour

I copied !

# Lesson 3 Problems 1-4
# Name: 4orty4
# Time: 4:00


##                Problem 1
## 7 * 3   +   9 * 1   +   20 * 1   ==   50
## 7 * 6   +   9 * 1   +   20 * 0   ==   51
## 7 * 1   +   9 * 5   +   20 * 0   ==   52
## 7 * 2   +   9 * 2   +   20 * 1   ==   52
## 7 * 5   +   9 * 2   +   20 * 0   ==   53
## 7 * 0   +   9 * 6   +   20 * 0   ==   54
## 7 * 1   +   9 * 3   +   20 * 1   ==   54
## 7 * 2   +   9 * 0   +   20 * 2   ==   54
## 7 * 4   +   9 * 3   +   20 * 0   ==   55

##              Problem 2
## For package sizes 6,9 and 20 six consecutive
## solutions prove that any higher number can
## also be purchased, because any combination can
## be increased by six by adding an additional
## package of six. For different package sizes,
## (n) consecutive solutions must be found, where
## (n) = the size of the smallest package.

##             Problems 3 and 4
## Solution condensed into one program. Tuple 'packages'
## can be changed to any other non-zero package sizes,
## provided the smallest package is listed first.

# packages[1]*x + packages[2]*y + packages[3]*z = n
# This program will find the highest whole number <200
# that can be purchased given the package sizes.

# Change package size by changing these values
# Smallest package size must be entered first for the program
# to function correctly
packages = (6,9,20)

#initialize values
total = 0
x, y, z = 0, 0, 0
n=0
solCounter = 0
isSolFound = 0
bestSoFar = 0

# For each x, y and z all values are tested between 0 and (n/package size + 1)

for n in range (1, 200):
    for x in range (0, (n/packages[0]+1)): 
        for y in range(0, (n/packages[1]+1)):
            for z in range(0, (n/packages[2]+2)):
                total = packages[0]*x + packages[1]*y + packages[2]*z
                if total == n:
                    print packages[0],'*',x,'  +  ',packages[1],'*',y,'  +  ',packages[2],'*',z,'  ==  ',total
                    isSolFound = 1
    #the loop continues even if a solution is found
    #not ideal but not sure how to break out of all 3 for loops
    #at once.

    if isSolFound == 1:
        solCounter += 1
        isSolFound = 0
    else:
        solCounter = 0
        bestSoFar = n # Stops when consecutive solutions = smallest package size
    if solCounter == packages [0]:
        break #breaks the loop so it doesn't have to try all 200 n's

print 'Package sizes are', packages[0], packages[1],'and', packages[2]               
print 'Largest number that can not be bought in exact quantity:', bestSoFar
conwayblue (Self-grade: Pretty good)
Submitted 1 year ago | Permalink | Time spent: 1 day

Big time beginner here: Thanks to those who posted their homework and gave some ideas to run through.

#Problem Set 2 (Part 1)
#Name: conwayblue

#Problem 1-------------------------------------------------------


def nuggets(totalNuggets):
    """needs total number of nuggets"""

    for pack20 in range(0, totalNuggets / 20 + 1):
        for pack9 in range(0, totalNuggets / 9 + 1):
            for pack6 in range(0,totalNuggets / 6 + 1):
                
                totalNuggetsCalc = 20*pack20 + 9*pack9 + 6*pack6
                if totalNuggetsCalc == totalNuggets and pack6 > -1:
                    return (pack6, pack9, pack20)
    return(None, None, None)
     

def mcdonalds():
    """will ask how many total nuggets"""
    
    totalNuggets = int(raw_input("How many total nuggets do you want? "))
    pack6, pack9, pack20 = nuggets(totalNuggets)

    if pack6 == None:
        print "You can't buy that many nuggets"
    else:
        print "You could buy", pack6, "six packs"
        print "You could buy", pack9, "nine packs"
        print "You could buy", pack20, "twenty packs"


#Problem 2--------------------------------------------------
        

def nuggetrange(startnumber):
    """needs a number and will give you the possible number packs for the next 6"""

    for each in range(startnumber, startnumber+7):
        pack6, pack9, pack20 = nuggets(each)
        if pack6 == None:
            print "You can\'t have", each, "nuggets dummy!"
        else:
            print "For", each, "nuggets you need", pack6, "six packs", pack9, "nine packs", pack20, "twenty packs"


#Problem 3---------------------------------------------------


def maxNonNugget():

    notNuggetFriendly = []

    for nuggetCount in range(0,50):

        packList = nuggets(nuggetCount)

        if packList[0] == None:

            notNuggetFriendly.append(nuggetCount)


    print "Largest number of McNuggets that cannot be bought in exact quantity: ", notNuggetFriendly[-1]
            
        
#Problem 4--------------------------------------------------------

def crazyNugget():
    
    packages = (6,9,20)
    notNuggetFriendly = 0
    foundRow = 0

    for totalNuggets in range(0,200):
        
        friendly = False

        for a in range(0, totalNuggets + 1):
            for b in range(0, totalNuggets + 1):
                for c  in range(0, totalNuggets + 1):
                    runningCalc = (a * packages[0]) + (b * packages[1]) + (c * packages[2])
                    if runningCalc == totalNuggets:
                        friendly = True

        if friendly:
            foundRow += 1
            if foundRow == packages[0]:
                break
        else:
            foundRow = 0
            notNuggetFriendly = totalNuggets

    print "Given sizes %s, %s, and %s, the largest number of nuggets than can't be purchased is %s" % (packages[0], packages[1], packages[2], notNuggetFriendly)



                



    

    
4orty4 (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 3 hours

I started from scratch 3 times on this one, but ended up with a straightforward program that I think does its job well. Comments are welcome. I'm enjoying looking at some of the other submissions but there's a lot of syntax I'm not familiar with yet. I'm looking forward to the next lessons!

# Lesson 3 Problems 1-4
# Name: 4orty4
# Time: 4:00


##                Problem 1
## 7 * 3   +   9 * 1   +   20 * 1   ==   50
## 7 * 6   +   9 * 1   +   20 * 0   ==   51
## 7 * 1   +   9 * 5   +   20 * 0   ==   52
## 7 * 2   +   9 * 2   +   20 * 1   ==   52
## 7 * 5   +   9 * 2   +   20 * 0   ==   53
## 7 * 0   +   9 * 6   +   20 * 0   ==   54
## 7 * 1   +   9 * 3   +   20 * 1   ==   54
## 7 * 2   +   9 * 0   +   20 * 2   ==   54
## 7 * 4   +   9 * 3   +   20 * 0   ==   55

##              Problem 2
## For package sizes 6,9 and 20 six consecutive
## solutions prove that any higher number can
## also be purchased, because any combination can
## be increased by six by adding an additional
## package of six. For different package sizes,
## (n) consecutive solutions must be found, where
## (n) = the size of the smallest package.

##             Problems 3 and 4
## Solution condensed into one program. Tuple 'packages'
## can be changed to any other non-zero package sizes,
## provided the smallest package is listed first.

# packages[1]*x + packages[2]*y + packages[3]*z = n
# This program will find the highest whole number <200
# that can be purchased given the package sizes.

# Change package size by changing these values
# Smallest package size must be entered first for the program
# to function correctly
packages = (6,9,20)

#initialize values
total = 0
x, y, z = 0, 0, 0
n=0
solCounter = 0
isSolFound = 0
bestSoFar = 0

# For each x, y and z all values are tested between 0 and (n/package size + 1)

for n in range (1, 200):
    for x in range (0, (n/packages[0]+1)): 
        for y in range(0, (n/packages[1]+1)):
            for z in range(0, (n/packages[2]+2)):
                total = packages[0]*x + packages[1]*y + packages[2]*z
                if total == n:
                    print packages[0],'*',x,'  +  ',packages[1],'*',y,'  +  ',packages[2],'*',z,'  ==  ',total
                    isSolFound = 1
    #the loop continues even if a solution is found
    #not ideal but not sure how to break out of all 3 for loops
    #at once.

    if isSolFound == 1:
        solCounter += 1
        isSolFound = 0
    else:
        solCounter = 0
        bestSoFar = n # Stops when consecutive solutions = smallest package size
    if solCounter == packages [0]:
        break #breaks the loop so it doesn't have to try all 200 n's

print 'Package sizes are', packages[0], packages[1],'and', packages[2]               
print 'Largest number that can not be bought in exact quantity:', bestSoFar

Comments:

wolfei
5 months ago

to break from a loop i think there is a break keyword to do this

Sign up or log in to comment

a3k3 (Self-grade: Outstanding)
Submitted 1 year ago | Permalink | Time spent: 6 hours

Problem Set 2 - Diophantine Equation

# Amy Karoline
# Course 600
# Problem Set 2, Diophantine Equations - McNuggets
# Time: Problem 1: 3 hrs 15 mins, Problem 2: 45 mins
# Problem 3: 45 mins, Problem 4: 1 hr 30 mins
# 01242011
####

from math import *

## 6a + 9b + 20c = n McNuggets Diophantine equation
##
## Problem 1:
## Show it's possible to buy exactly 50, 51, 52, 53, 54, and 55 McNuggets by
## finding solutions to the Diophantine equation. List the combos of 6, 9, and
## 20 packs of Nuggets you need to buy in order to get each of the exact amounts

a = 0
b = 0
c = 0
n = 0
soln = 0
solns = []
possibleN =[]

# creates lists of possible n values and solutions to the n values
while n <= 55:
    solns.append('nada')
    for a in range(0, n/6+1):
        for b in range(0, n/9+1):
            for c in range(0, n/20+1):
                soln = 6*a + 9*b + 20*c
                if soln == n:
                    if solns[n] == 'nada':
                        solns.insert(n,[a,b,c])
                        possibleN.append(n)
    n += 1
print 'Problem 1:'        
for y in range(50,56):
    print 'For ',y,' nuggets, buy ', solns[y][0],' 6-pack(s), ', solns[y][1],' 9-pack(s), and ', solns[y][2],' 20-pack(s)'

## Then show how, given solutions for 50-55. you can also derive solutions
## for 56-65.
print ''

n=0
soln = 0

for n in range(56,66):
    for z in range(50,56):
        for w in range(1,3):
            if n == 6*w + 6*solns[z][0] + 9*solns[z][1] + 20*solns[z][2]:
                solns.insert(n,[solns[z][0]+w, solns[z][1], solns[z][2]])
                possibleN.append(n)
                
for y in range(56,66):
    print 'For ',y,' nuggets, buy ', solns[y][0],' 6-pack(s), ', solns[y][1],' 9-pack(s), and ', solns[y][2],' 20-pack(s)'

##Problem 2:
##    This theorem is true because the smallest set of McNuggets possible to buy is
##    6. The range from x to x+5 contains 6 sequential values, therefore, every x+n
##    beyond x+5 will be one of the values in the range from x to x+5 plus a multiple
##    of 6.  x+n = 6*z + (one of x to x+5), where z is an integer

##Problem 3: Solving a Diophantine equation
##    Write an exhaustive search to find the largest number of McNuggets that
##    cannot be bought in exact quantity.
##    Mmmm... this is making me crave nuggets.
print ''
print 'Problem 3:'        

a=0
b=0
c=0
n=0
sol=0
consecutiveN = 0        
impossibleN=[]

for n in range(1,200):
    ans=False
    for a in range(0, n/6+1):
        for b in range(0, n/9+1):
            for c in range(0, n/20+1):
                sol = 6*a + 9*b + 20*c
                if sol == n:
                    ans = True
    if ans:
        consecutiveN += 1
        if consecutiveN == 6:
            print 'The largest impossible quantity of McNuggets is: ',impossibleN[-1]
    else:
        impossibleN.append(n)
        consecutiveN = 0


##Problem 4:
##    Use exhaustive search to find the largest number less than 200 of McNuggets
##    that cannot be bought in exact quantity. Sometimes there is not largest value
##    so we have to have the limit of 200 to protect for infinite looping.
print ''
print 'Problem 4:'        

x=1
y=9
z=500

sol=0
consN=0
impN=[]
n=0

packages = (x,y,z)
foundLargest = False

for n in range(1,200):
    ans=False
    for a in range(0, n/packages[0]+1):
        for b in range(0, n/packages[1]+1):
            for c in range(0, n/packages[2]+1):
                sol = packages[0]*a + packages[1]*b + packages[2]*c
                if sol == 1:
                    foundLargest = False
                elif sol == n:
                        ans = True
    if ans:
        consN += 1
        if consN == 6 and packages[0] != 1:
            print 'Given package sizes %d, %d, %d, the largest number of McNuggets that cannot be bought in exact quantity is: %d' % (packages[0], packages[1], packages[2], impN[-1])
            foundLargest = True
    else:
        impN.append(n)
        consN = 0
if not foundLargest:
    print 'There is no largest impossible purchaseable quantity of nuggets under 200 for package sizes ',x,', ',y,', ',z,'.'


        
    


    
rfh (Self-grade: Outstanding)
Submitted 1 year ago | Permalink
# Problem 1 Part 1

lookingFor = (50, 51, 52, 53, 54, 55)
for a in range(0, 55 / 6 + 1):
    for b in range(0, 55 / 9 + 1):
        for c in range(0, 55 / 20 + 1):
            solution = (6 * a) + (9 * b) + (20 * c)
            if solution in lookingFor:
                print "Combination found for %d: (%d packages of 6, %d packages of 9, %d packages of 20)" % (solution, a, b, c)

# Problem 2
#
# Because we know there is a valid combination for purchasing 50, 51,
# 52, 53, 54 and 55 Chicken McNuggets, and because we are able to
# purchase packages in sizes 6 or 9, we know there must be valid combinations 
# for purchasing 56-65 as we only need to add another package of "6" to our
# solution for purchasing "50" to get "56", another package of "6" to
# our solution for purchasing "51" to get "57", another package of "6"
# to our solution for purchasing "52" to get "58", another package of "6"
# to our solution for purchasing "53" or another package of "9" to our
# solution for puchasing "50" to get "59", etc.


# Problem 3
#
# Use this to write an exhaustive search to find the *largest* number of
# chicken nuggets that *cannot* be bought

foundInARow = 0
maxThatCannotBePurchased = 0

for i in range(0, 50):
    canPurchaseThisAmount = False

    for a in range(0, i / 6 + 1):
        for b in range(0, i / 9 + 1):
            for c in range(0, i / 20 + 1):
                solution = (6 * a) + (9 * b) + (20 * c)
                if solution == i:
                    canPurchaseThisAmount = True

    if canPurchaseThisAmount:
        foundInARow += 1
        if 6 == foundInARow:
            break;
    else:
        foundInARow = 0
        maxThatCannotBePurchased = i

print "Largest number of McNuggets that cannot be bought in exact quantity: %d" % maxThatCannotBePurchased

# Problem 4
#
# Assume that the variable packages is bound to a tuple of length 3, the
# values of which specify the sizes of the packages, ordered from
# smallest to largest. Write a program that uses exhaustive search to
# find the largest number (less than 200) of McNuggets that cannot be
# bought in exact quantity.

packages = (15, 24, 32)
maxThatCannotBePurchased = 0

for i in range(0, 200):
    canPurchaseThisAmount = False

    for a in range(0, i / packages[0] + 1):
        for b in range(0, i / packages[1] + 1):
            for c in range(0, i / packages[2] + 1):
                solution = (packages[0] * a) + (packages[1] * b) + (packages[2] * c)
                if solution == i:
                    canPurchaseThisAmount = True

    if canPurchaseThisAmount:
        foundInARow += 1
        if packages[0] == foundInARow:
            break;
    else:
        foundInARow = 0
        maxThatCannotBePurchased = i
 
print "Given that sizes %d, %d, and %d, the largest number of McNuggets that cannot be bought in exact quantity is: %d" % (packages[0], packages[1], packages[2], maxThatCannotBePurchased)
wborskey (Self-grade: Pretty good)
Submitted 1 year ago | Permalink

I built a list then organized and parsed it. Please comment.

#Solutions to problems 1 and 2
A	B	C   	         D
6	9	20	= 	 X
---------------------------
2	2	1      =      50
5	0	1	=	51
2	0	2	=	52
4	1	1	=	53
1	1	0	=	54
1	1	2	=	55
3	2	1	=	56
6	0	1	=	57
3	0	2	=	58
5	1	1	=	59
2	1	0	=	60
2	1	2	=	61	
4	2	1	=	62
7	0	1	=	63
4	0	2	=	64
6	1	1	=	65

Every six iterations, A increases by 1; B repeats the pattern: 0,0,1,1,1 and C repeats the pattern:
1,1,2,1,0,2. When D increases by 6 A increases by 1.

#Solutions to problems 3 and 4
packages = (6, 9, 20)
BestSoFar = packages[0]-1
n = 1
counter = 0

def BuildTable(packages):
	LookUpTable = []
	sum = 0
	for first in range(0, 10):
		for second in range(0, 10):
			for third in range(0, 10):
				sum = first*packages[0]+second*packages[1]+third*packages[2]
				LookUpTable.append(sum)
	LookUpTable = list(set(LookUpTable))
	return LookUpTable
	
array = BuildTable(packages)

while n < len(array):
	if array[n] - array[n-1] == 1:
		counter += 1
	else:	
		counter = 0
	if counter == packages[0]:
		BestSoFar = array[n-packages[0]] - 1
	n += 1
	
print "Largest number of McNuggets that cannot be bought in exact quantity:", BestSoFar
print "Given sizes package sizes", packages[0], ",", packages[1], "and", packages[2], ", the largest number of McNuggets that cannot be bought in exact quantity is:", BestSoFar  			
DvorakAJS (Self-grade: Could be better)
Submitted 1 year ago | Permalink

Wrote a first script to calculate the first problem.

If you can buy x nuggets and x+6 you can buy any nuggets by just adding 6 everytime (you may have to tweak a bit but that is the general idea)

script is written for problem 3, problem 4 is comming up (forgot about it but it doesn't look that hard)

grtz and thanks for feedback!

#variables
bestSoFar = 0                               # variable that keeps track of largest number
                                            # of McNuggets that cannot be bought in exact quantity
packages = (6,9,20)                         #variable that contains package sizes
number_of_nuggets=1
number=0                                    #the number that changes to reach our wanted number of nuggets
count=0                                     #if 6 we have the largest possible number

packs_of_small=0                            #any way to declare all these in a shorter way?
packs_of_medium=0
packs_of_large=0
max_packs_large=0 
max_packs_medium=0
max_packs_small=0


#function
def brute_force_and_calculate():                                          #actual bruteforcing
    global packs_of_large
    global packs_of_medium
    global packs_of_small
    global number
    for packs in range(0,max_packs_large+1):			 
        packs_of_large=packs       
        for packs in range(0,max_packs_medium+1):
            packs_of_medium=packs
            for packs in range(0,max_packs_small+1):
                packs_of_small=packs
                number = (6*packs_of_small)+(9*packs_of_medium)+(20*packs_of_large)   #used to be calculate_number() on it's own, but this actually works
                if number == number_of_nuggets:
                  return number
                  return packs_of_large
                  return packs_of_small
                  return packs_of_medium

#program itself
while number_of_nuggets <150:   		# only search for solutions up to size 150
                            			# complete code here to find largest size that cannot be bought
    max_packs_small=(number_of_nuggets/packages[0])+1         
    max_packs_medium=(number_of_nuggets/packages[1])+1
    max_packs_large=(number_of_nuggets/packages[2])+1                                  #calculate packs per number
    brute_force_and_calculate()
    if number == number_of_nuggets:                         # if it's what we want the counter goes up, 6 means we have to stop
        count+=1
        if count >6:
            print 'the largest number that we cannot create is:',bestSoFar
            number_of_nuggets=150                           #stop the while loop
            
    else: 
        bestSoFar=number_of_nuggets
        count=0                                             #reset counter
    number_of_nuggets+=1
    
                        
print 'done'
jbuck0 (Self-grade: Outstanding)
Submitted 1 year ago | Permalink

1. 6(2) + 9(2) + 20(1) = 12 + 18 + 20 = 50 McNuggets 6(1) + 9(5) + 20(0) = 6 + 45 + 0 = 51 McNuggets 6(2) + 9(0) + 20(2) = 12 + 0 + 40 = 52 McNuggets 6(1) + 9(2) + 20(1) = 6 + 18 + 20 = 53 McNuggets 6(0) + 9(6) + 20(0) = 0 + 54 + 0 = 54 McNuggets 6(1) + 9(1) + 20(2) = 6 + 9 + 40 = 55 McNuggets

50 + 6 = 56 McNuggets 51 + 6 = 57 McNuggets 52 + 6 = 58 McNuggets 53 + 6 = 59 McNuggets 54 + 6 = 60 McNuggets 55 + 6 = 61 McNuggets 50 + 6 + 6 = 62 McNuggets 51 + 6 + 6 = 63 McNuggets 52 + 6 + 6 = 64 McNuggets 53 + 6 + 6 = 65 McNuggets

  1. Given package sizes of 6, 9, and 20 and the possibility of buying between 'x' and 'x+5' McNuggets at once, we can assume that any number of McNuggets larger than 'x' can be bought because 'x+6' McNuggets would simply be the original 'x' amount of McNuggets plus an extra box of six. From that we can figure out that 'x+7' McNuggets would be 'x+1' McNuggets plus an extra box of six, and so forth.
# Problem Set 2

# pt. 3

n = 1
csols = 0
solution = 0
found = 0

while csols < 6 :

    found = 0

    for a in range (0, 9) :

        for b in range (0, 6) :

            for c in range (0, 3) :

                if (6 * a) + (9 * b) + (20 * c) == n :
                   found = 1

    if found == 1 :

        csols += 1

    else :

        csols = 0
        solution = n

    n += 1

print "Largest number of McNuggets that cannot be bought in exact quantity:", solution


# pt. 4

bestSoFar = 0
packages = (6,9,20)

for n in range(1, 200) :

    exact = False
    for a in range (0, 33) :

        for b in range (0, 22) :

            for c in range (0, 10) :

                if (packages[0] * a) + (packages[1] * b) + (packages[2] * c) == n :

                    exact = True
                    break

    if exact == False and bestSoFar < n :

        bestSoFar = n

print "Given package sizes " + str(packages[0]) + ", " + str(packages[1]) + ", and " + str(packages[2]) + ", the largest number of McNuggets that"
print "cannot be bought in exact quantity is " + str(bestSoFar) + "."
pyBoogie (Self-grade: Pretty good)
Submitted 1 year ago | Permalink
# Problem Set 2 (Part 4)                                                                              
# Name: Boogie Devera                                                                                 
# Collaborators: None                                                                                 
# Time: 00:30                                                                                         

bestSoFar = 0

packages = (6, 9, 20)

for n in range(1,200):

    exactQtyFlag = False # does not solve the diophantine equation                                    

    for a in range(0,10):
        for b in range(0,10):
            for c in range(0,10):
                calc =  a * packages[0] + b * packages[1] + c * packages[2]
                if n == calc:
                    exactQtyFlag = True
                    break

    if not exactQtyFlag and bestSoFar < n:
        bestSoFar = n

print "Given packages sizes <6>, <9>, and <20>, the largest number of McNuggets that"
print "cannot be bought in exact quantity is: ", bestSoFar

Comments:

kday
1 year ago

Nice job! Very concisely written.

pyBoogie
1 year ago

Oh thanks kday. Just wanted to keep it simple. I wanted to use a function but this session has not discussed functions yet.

Sign up or log in to comment

kpmoore (Self-grade: Outstanding)
Submitted 1 year ago | Permalink
#code to calculate possible McNugget combinations up to n = 55 nuggets

n=0
a=0
b=0
c=0
while n < 55:
    if 6*a + 9*b + 20*c < n:
        a = a + 1
    elif 6*a + 9*b + 20*c > n:
        a = 0
        b = b + 1
        if 9*b > n:
            b = 0
            c = c + 1
            if 20*c > n:
                c = 0
                n = n + 1 
    elif 6*a + 9*b + 20*c == n:        
        print 'For', n, 'McNuggets, a =', a, ', b =', b, ', c =', c
        a = a + 1

#code to calculate the largest quantity of McNuggets which cannot be obtained using the three sizes small, medium, and large

bestSoFar = 0     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
packages = (6,9,20)   # variable that contains package sizes
(small, medium, large) = packages
for n in range(1, 200):   # only search for solutions up to size 200
    a = 0
    b = 0
    c = 0
    while large*c < n:
        if small*a + medium*b + large*c < n:
            a = a + 1
        elif small*a + medium*b + large*c > n:
            a = 0
            b = b + 1
            if medium*b > n:
                b = 0
                c = c + 1
        if small*a + medium*b + large*c == n:
            break
        elif large*c > n:
            print n, "McNuggets cannot be bought in exact quantity."
            bestSoFar = n
print "Largest number of McNuggets that cannot be bought in exact quantity:", bestSoFar
 
chrcoe (Self-grade: Pretty good)
Submitted 1 year ago | Permalink
###==================================================
## Problem Set 2 (Part I)
## Time: 1:10
###==================================================

currentTesNum = 1

lastNum = 0

solutions = 0

a = 6
b = 9
c = 20


while solutions<6: #when we find 6 consecutive solutions...
    solved=False
    #Ax+By+Cz = n Diophantine Equation
    for countForA in range(0,a+1): ##nested for loop helps count 'all feasible solutions'
        for countForB in range(0,b+1):
            for countForC in range(0,c+1): 
                if currentTestNum == a*countForA + b*countForB + c*countForC:
                    solved = True
                    #print currentTestNum
    if solved == True:
        solutions += 1
    else:
        lastNum = currentTestNum
        solutions = 0

    currentTestNum += 1

print "Largest number of McNuggets that cannot be bought in exact quantity:",lastNum

#######################################################

###==================================================
## Problem Set 2 (Part II)
## Time: 25 
###==================================================


bestSoFar = 0     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
packages = (6,9,20)   # variable that contains package sizes

for n in range(1, 150):   # only search for solutions up to size 150
    ## complete code here to find largest size that CANNOT be bought
    ## when done, your answer should be bound to bestSoFar
    #Ax+By+Cz = n Diophantine Equation
    solved=False
    for countForA in range(0,packages[0]+1):
        for countForB in range(0,packages[1]+1):
            for countForC in range(0,packages[2]+1):
                if n == packages[0]*countForA + packages[1]*countForB + packages[2]*countForC:
                    solved = True
                    #print n
    if solved != True:
        bestSoFar = n
        
    
print "Given package sizes",packages[0],",",packages[1],", and",packages[2],'\n'
print "Largest number of McNuggets that cannot be bought in exact quantity:",bestSoFar
mrphud (Self-grade: Pretty good)
Submitted 1 year ago | Permalink
##Problem #1
#We wish to show there are solutions to the eq 6a + 9b + 20c = n
#where n is 50 - 55

n = range(50,56)                            #create the list for which to check

for i in n:                                 #search the list by setting n
    for a in range(0,11):                   #for some n search a
        for b in range(0,8):                #for some n, a search b
            for c in range(0,4):            #for some n, a, b search c
                if 6*a + 9*b + 20*c == i:   #test if this is true. If yes print. If not do the try the next c
                    print 'we have a solution!'
                    print a,b,c, 'yields', i

##Problem #2
#Here we chose to show that if 50 - 55 can be made in exact quantity then so can
#any number greater than 55

newset = range(56,66)                       #adptation of previous program. simply new set of numbers to check

for i in newset:
    for a in range(0,15):
        for b in range(0,15):                   
            for c in range(0,5):
                if 6*a + 9*b + 20*c == i:
                    print 'we have a solution!'
                    print a,b,c, 'yields', i

##Problem 3
#This program will search for the largest value that cannot be made
#in exact quantity

highnum = range(1,50)                       #range of numbers to check
good = (6,)                                 #initiates the tuple of values that can be found
duds = ()                                   #initiates the tuple of values that can't be found

for i in highnum:
    for a in range(0,50/6 + 1):
        for b in range(0,50/9 + 1):
            for c in range(0,50/20 + 1):
                if 6*a + 9*b + 20*c == i and i != good[-1]:       #search for numbers that can be found and            
                    good += (i,)                                  #put them in good. i != good[-1] checks if
                                                                  #the value is already in good
n = 1
b = 0                                       #This added code takes what is not in good and puts it in duds.
while n < 50:
    if n != good[b]:                        #check if it is not in good
        duds += (n,)                        #and put it in dud
        n += 1
    else:
        b += 1                              #b is meant to check if there is double counting. it is redundant now that  
        n += 1                              #i != good[-1] is checked

print 'The largest number of McNuggets that cannot be bought in exact quantity is: ' + str(duds[-1])

##Problem #4
#This adaptation performs a search for vaules less than 200 that cannot be found by combinations of 3 separate package sizes
#This is a generalized form of the previous code.

pck1 = input('Enter the smallest of the packages: ')
pck2 = input('Enter the medium of the packages: ')
pck3 = input('Enter the largest of the packages: ')
package = (pck1, pck2, pck3)
print 'The package quantities you chose were', package

good1 = (pck1,)             
duds1 = ()
limit = range(1,201)                            

for i in limit:
    for a in range(0, 200/pck1 + 2):
        for b in range(0, 200/pck2 + 2):
            for c in range(0, 200/pck3 + 2):
                if pck1*a + pck2*b + pck3*c == i and i != good1[-1]:                   
                    good1 += (i,)

n = 1
b = 0
while n < 201:
    if n != good1[b]:
        duds1 += (n,)
        n += 1
    else:
        b += 1
        n += 1

print 'Given package', package, 'the largest quantity of McNuggets, less that 200, that cannot be bought is: ', duds1[-1]


Nicholas123 (Self-grade: Outstanding)
Submitted 1 year ago | Permalink
###PS2a###

n = 1					#The desired total number of nuggets, starting with 1
maxTest = 20		#the largest polynomial coefficient to test
cantObtain = 0  	#last found number can't be obtained by combo of 6, 9, 20
consecutive = 0 	#number of consecutive combinations found
found = False		#have we found a valid combination?

while consecutive < 6:
	found = False
	#these for loops try every combination of coefficients up to maxTest
	for a in range(maxTest):
		for b in range(maxTest):
			for c in range(maxTest):
				#print 'a:{0:2d} b:{1:2d} c:{2:2d} -> {3:4d}'.format(a, b, c, 6*a+9*b+20*c)
				if 6*a+9*b+20*c == n:
					print 'Found a combination for', n
					found = True					
	if found == False:
		cantObtain = n
		consecutive = 0
	elif found == True:
		consecutive += 1
	n += 1
	
print 'The last unobtainable number was', cantObtain



###PS2b###

n = 1					#The desired total number of nuggets, starting with 1
maxTest = 40		#the largest polynomial coefficient to test
cantObtain = 0  	#last found number can't be obtained by combo of tuple box
consecutive = 0 	#number of consecutive combinations found
found = False		#have we found a valid combination?

#box = (1, 2, 3)
#box = (6, 9, 20)
#box = (3, 10, 12)
#box = (4, 6, 9)
#box = (2, 4, 6)
box = (7, 9, 11)

while consecutive < 6:
	found = False
	#these for loops try every combination of coefficients up to maxTest
	for a in range(maxTest):
		for b in range(maxTest):
			for c in range(maxTest):
				#print 'a:{0:2d} b:{1:2d} c:{2:2d} -> {3:4d}'.format(a, b, c, 6*a+9*b+20*c)
				if box[0]*a+box[1]*b+box[2]*c == n:
					print 'Found a combination for', n
					found = True					
	if found == False:
		cantObtain = n
		consecutive = 0
	elif found == True:
		consecutive += 1
		if n >= 200: 
			print 'Limit exceeded, probably no answer'
			break
	n += 1

print "Given package sizes " + str(box[0]) + ", " + str(box[1]) + " and " + str(box[2]) + " the largest number of McNuggets that cannot be bought in exact quantity is: " + str(cantObtain)
dimebucker (Self-grade: Pretty good)
Submitted 1 year ago | Permalink

Used a program to find the answers to problem 1 with problem 2 answered in comments at the bottom.

used the same program for problems 3 and 4.

# Problem Set 2
# Name: Matt Coley
# Time:
#

nugPk1 = 6
nugPk2 = 9
nugPk3 = 20
nugTotal = 0
nugCombo = 51
nugPk1Cnt = 0
nugPk2Cnt = 0
nugPk3Cnt = 0

# loop through each type of nugget limiting the test to the desired amount / each package size
# also including 0 as a size
while nugPk1Cnt < (nugCombo/nugPk1+1):
    nugPk2Cnt = 0
    nugTotal = nugPk1Cnt*nugPk1
    while nugPk2Cnt < (nugCombo/nugPk2+1):
        nugPk3Cnt = 0
        nugTotal = (nugPk1Cnt*nugPk1) + (nugPk2Cnt*nugPk2) + (nugPk3Cnt*nugPk3)
        while nugPk3Cnt < (nugCombo/nugPk3+1):
            if nugTotal == nugCombo:
                print nugTotal, "nuggets can be exactly obtained buying", nugPk1Cnt, nugPk1, \
                "packs,", nugPk2Cnt, nugPk2, "packs, and", nugPk3Cnt, nugPk3, "packs."
            nugTotal += nugPk3
            nugPk3Cnt += 1
        nugTotal += nugPk2
        nugPk2Cnt += 1
    nugTotal += nugPk1
    nugPk1Cnt += 1

# Any number above 55 can now be obtained by multiples of 6.  For example, 56 can be obtained by 50 + 6.
# 65 can be obtained by 53 + 6 = 59 + 6 = 65.  Since the next available number past 50-55 is at least 6 numbers
#   away from the start and one of the nugget sizes is 6, you can continue to generate groupings of 6 off into
#   infinity.  50-55, 56-61, 62-67, etc.

# Problem Set 2a & 2b
# Name: Matt Coley
# Time:
#

nugPk1 = 6
nugPk2 = 9
nugPk3 = 20
nugTotal = 0
nugCombo = 200
nugPk1Cnt = 0
nugPk2Cnt = 0
nugPk3Cnt = 0
testNum = 0
lastConseq = 0
lastUACnt = 0
conseqChk = 0
conseqCnt = 0

while testNum < nugCombo:
    conseqChk = 0
    testNum += 1
    nugPk1Cnt = 0
    while nugPk1Cnt < (nugCombo/nugPk1+1):
        nugPk2Cnt = 0
        nugTotal = nugPk1Cnt*nugPk1
        while nugPk2Cnt < (nugCombo/nugPk2+1):
            nugPk3Cnt = 0
            nugTotal = (nugPk1Cnt*nugPk1) + (nugPk2Cnt*nugPk2) + (nugPk3Cnt*nugPk3)
            while nugPk3Cnt < (nugCombo/nugPk3+1):
                if testNum == nugTotal:
                    conseqChk = 1
                else:
                    lastUACnt = testNum
                nugTotal += nugPk3
                nugPk3Cnt += 1
            nugTotal += nugPk2
            nugPk2Cnt += 1
        nugTotal += nugPk1
        nugPk1Cnt += 1
    if conseqChk == 1:
        conseqCnt += 1
    else:
        conseqCnt = 0
    if conseqCnt == nugPk1:
        print lastUACnt, "is the largest exact unpurchasable amount."
if conseqCnt < nugPk1:
    print lastUACnt, "is the largest exact unpurchasable amount."
NawXela (Self-grade: Outstanding)
Submitted 1 year ago | Permalink
#Problem Set #2
#Name: Alex Wan
#Time: Far too long
#Collaborators: CuriousReef

#Problem 1
#McNuggets come in packs of 6, 9, and 20. Show that it is possible to buy 
#exactly 50, 51, 52, 53, 54, and 55 McNuggets using this Diophantine equation:
#6a + 9b + 15c = n, where n is the number of McNuggets.
#List all combinations.


#I tried finding it for any range, however I'm not sure how to fill the values
#between the first and last values. So I'll just go from 50 to 55.

nuggetrange = (50, 51, 52, 53, 54, 55)

for a in range (0, 20):
        for b in range (0, 20):
                for c in range (0, 20):
                        n = 6*a+9*b+20*c;
                        if n in nuggetrange:
                                print (a, b, c, n)

##(0, 6, 0, 54)
##(1, 1, 2, 55)
##(1, 3, 1, 53)
##(1, 5, 0, 51)
##(2, 0, 2, 52)
##(2, 2, 1, 50)
##(3, 4, 0, 54)
##(4, 1, 1, 53)
##(4, 3, 0, 51)
##(5, 0, 1, 50)
##(6, 2, 0, 54)
##(7, 1, 0, 51)
##(9, 0, 0, 54)

#Problem 2                           
#Theorem: If it is possible to buy x, x+1,...,x+5 sets of McNuggets for some x,
#then it is possible to buy any number of McNuggets greater than or equal to x,
#given that McNuggets come in sets of 6, 9, and 20.
#Explain why this is true.

#Um... because it is? Well, I know x must at least be bigger than 6, because that
#is the minimum amount you can buy. But 7 (6+1) and 8 (6+2) are impossible to buy.
#The reason lies in the fact that the smallest they come in is 6. If you can get
#a combination for any number from x to x+5, then x+6 would merely be another set
#of 6 McNuggets. For example, x+11 would be broken down into x+5 and 6. If you can
#get a combination for x+5 McNuggets, all you need is another set of 6. The theorem
#holds true for sets of 6 and 9, or 6 and 20, or 6 and any number.

#Problem 3:
#Find the largest amount of McNuggets that cannot be bought in exact quantity. 
#Print the following line at the end:
#"Largest number of McNuggets that cannot be bought in exact quantity: <n>"

#My idea is to start n at 1, and keep increasing n until we get six consecutive solutions.
#Of course, it's always harder than it sounds. I'm not sure how I can get Python to
#record six consecutive solutions, and tell the program to stop if I do. The main problem
#lies in the fact that the solution generator does not generate n in sequential order.
#I might get solutions for 54, then 53, and then 50, making increasing the number useless.

#My solution lies in the ability to remove the first element in a queue. With a brute forced list of possible answers,
#I checked if the first element was exactly five less than the sixth element. If not, the first element was removed, and
#the test was repeated until an answer was found.

from collections import deque

rightanswers = []
answer = False
count = 0

for a in range (0, 20):
        for b in range (0, 20):
                for c in range (0, 20):
                        n = 6*a+9*b+20*c;
                        #print (a, b, c, n)
                        rightanswers.append(n)
                        rightanswers.sort()
                        rightanswers = list(set(rightanswers))

print rightanswers
rightanswers = deque(set(rightanswers))
while answer == False:
        if rightanswers[0] + 5 == rightanswers[5]:
                answer = True
                print possibleanswer, 'is the largest number of McNuggets that cannot be bought in exact quantity.'
        else:
                possibleanswer = rightanswers[0]
                rightanswers.popleft()

#Problem 4:
#Assign a tuple to be the coefficents of the variables in the diophantine equation.
#Then, exhaustively search for the largest number less than 150 that cannot be bought in exact quantity.

#I used the same code as atop, but added the restrictive template and user friendlied the code.

from collections import deque

bestSoFar = 0     # variable that keeps track of largest number of McNuggets that cannot be bought in exact quantity
first = int(input('Enter the first package size:'))
second = int(input('Enter the second package size:'))
third = int(input('Enter the third package size:'))
packages = [first,second,third]   # variable that contains package sizes
packages.sort()
x = packages[0]
y = packages[1]
z = packages[2]
rightanswers = []
finalanswers = []
answer = False

for a in range (0, 20):
        for b in range (0, 20):
                for c in range (0, 20):
                        n = x*a+y*b+z*c;
                        #print (a, b, c, n)
                        rightanswers.append(n)
                        rightanswers.sort()
                        rightanswers = list(set(rightanswers))
print rightanswers
rightanswers = deque(set(rightanswers))
while answer == False:
        if rightanswers[0] + packages[0] == rightanswers[x]:
                answer = True
        else:
                possibleanswer = rightanswers[0]
                rightanswers.popleft()

for n in range(1, 150): # only search for solutions up to size 150
        if n in rightanswers:
                finalanswers.append(n)
        if possibleanswer in range (1, 150):
                finalanswers.append(possibleanswer)
print finalanswers
bestSoFar = finalanswers[0]
print 'Given package sizes', x, y, z, 'the largest number of McNuggets that cannot be bought in exact quantity is:', bestSoFar
        ## complete code here to find largest size that cannot be bought
        ## when done, your answer should be bound to bestSoFar
        ## SUCCESS!                        

chip (Self-grade: Outstanding)
Submitted 1 year ago | Permalink
#Problem Set 2
#Name: chip
#Time: 4:00
#

#Problem 1
region = range(50, 55)

for a in range (0, 20):
	for b in range(0,20):
		for c in range(0,20):
			k = 6 * a + 9 * b + 20 * c;
			if k in region:
				print("{0:2}*6 + {1}*9 + {2}*20 = {3}".format(a,b,c,k));

#	2*6 + 2*9 + 1*20 = 50
#	5*6 + 1*9 + 0*20 = 51
#	2*6 + 0*9 + 2*20 = 52
#	1*6 + 3*9 + 1*20 = 53	
#	9*6 + 0*9 + 0*20 = 54
#	1*6 + 1*9 + 2*20 = 55

#Problem 2
"""
	Theorem is true because when we had all x, x+1,..., x+5 all next steps will repeat.
	For example if we has 54 nugets we can add 6 and get 60 or 51 + 6 =57.
	This works for any x, ...,  x+5 values
"""

#Problem 3
def can_buy(n, ax, bx, cx):
	for a in range(0,20):
		for b in range(0,20):
			for c in range(0,20):
				k = ax * a + bx * b + cx * c
				if k == n:
					return True
	return False

def solve(a,b,c):
	count = 0
	for n in range(1,200):
		if not can_buy(n,a,b,c):
			ans = n
			count = 0
		else:	count += 1
		if count == 6:	break
	print("Given package sizes <{0}>, <{1}>, <{2}>, the largest number of McNuggets that cannot be bought in exact quantity is: {3}".format(a,b,c,ans))


solve(6,9,20)

#Problem 4
solve(10,14,15)
Joe (Self-grade: Outstanding)
Submitted 1 year ago | Permalink

Diophantine equations

# Problem Set 2 (Part I)
# Name: Joe Li
# Time: 4:00
#

count=0                             # the number of successive n McNuggets can be bought
n=1                                 # n start from 1
a=0                                 # make a,b,c,recognizable
b=0
c=0                          
while count!=6:                     # do as following untill count=6
      while 6*a+9*b+20*c!=n:        # test if n McNuggets can be bought with the combination abc. if test fail, do as following
            if 6*a>n:               # if a exceeds the limit
                  a=0               # reset a
                  b+=1              # try next b
            elif 9*b>n:             # if b exceeds the limit
                  a=0               # reset a
                  b=0               # reset b
                  c+=1              # try next c
            elif 20*c>n:            # if c excceds the limit
                  a=0               # reset a
                  b=0               # reset b
                  c=0               # reset c
                  count=0           # reset count
                  m=n               # store last n cannot be bought to m
                  n+=1              # test next n
            else:                   # if none of a,b,c exceeds the limit
                  a+=1              # try next a
      else:                         # if pass the test
            count+=1                # count plus 1
            n+=1                    # try the next n
            a=0                     # reset a
            b=0                     # reset b
            c=0                     # reset c
else:                               # if got 6 successive n McNuggets can be bought,
      print 'Largest number of \
McNuggets that cannot \
be bought in exact \
quantity: <'+str(m)+'>'             # print the last n cannot be bought
                                    

# Problem Set 2 (Part II)
# Name: Joe Li
# Time: 3:00
#
bestSoFar=0                               # variable that keeps track of largest number of McNuggets that cannot be bought in exact quantity
package=(7,13,19)                          # variable that cantains package sizes             
x=package[0]
y=package[1]
z=package[2]
for n in range(1,200):                    # test n from 1 to 199
      m=1                                 # variable that remains 1 unless such n McNuggets can be bought with some combination
      for c in range(0,n/z+2):            # test c from 0 to n/z+1
            for b in range(0,n/y+2):      # test b from 0 to n/y+1
                  for a in range(0,n/x+2):# test a from 0 to n/x+1
                        if x*a+y*b+z*c==n:# if n McNuggets can be bought with such combination abc
                             m=0          # set m to 0
      if m==1:                            # if m hasn't been set to 0 which means there's no combination with whitch n McNuggets can be bought
            bestSoFar=n                   # assign such n to bestSoFar
print 'Given package sizes <'+str(x)+'>, \
<'+str(y)+'>, and <'+str(z)+'>, the largest \
number of McNuggets that cannot be bought \
in exact quantity is: <'+str(bestSoFar)+'>'
BTheMad (Self-grade: Pretty good)
Submitted 1 year ago | Permalink
# Problem 3
a = 1
b = 1
c = 1
eq = 6 * a + 9 * b + 20 * c

n = 200

max_a = n / 6 + 1
max_b = n / 9 + 1
max_c = n / 20 + 1

n_tuple = ()
for n in range(1, n):
    for a in range(0, max_a):
        for b in range(0, max_b):
            for c in range(0, max_c):
                eq = 6 * a + 9 * b + 20 * c
                if eq == n:
                    print n
                    print 'We found it: a =', a, ',  b=', b, ', c=', c
                    is_unique = True
                    for tmp_n in n_tuple:
                        if tmp_n == n:
                            is_unique = False
                    if is_unique:
                        n_tuple += (n,)
print n_tuple

maximum = 0
for max_n in range(1, n):
    if max_n not in n_tuple:
        maximum = max_n
        
print 'Largest number of McNuggets that cannot be bought in exact quantity: ', maximum


# Problem 4
bestSoFar = 0           # variable that keeps track of largest number
packages = (3,14,17)     # variable that contains package sizes

max_n = 150
max_values = (max_n/packages[0] +1, max_n/packages[1] + 1, max_n/packages[2] + 1)

n_tuple = ()
for n in range(1, max_n):   # only search for solutions up to size 150
    for a in range(0, max_values[0]):
        for b in range(0, max_values[0]):
            for c in range(0, max_values[0]):
                eq = packages[0] * a + packages[1] * b + packages[2] * c
                if eq == n:
                    is_unique = True
                    for tmp_n in n_tuple:
                        if tmp_n == n:
                            is_unique = False
                    if is_unique:
                        n_tuple += (n,)

print n_tuple
maximum = 0
for max_n in range(1, n):
    if max_n not in n_tuple:
        bestSoFar = max_n
        
print 'Given package sizes', packages[0], ',', packages[1], 'and', packages[2], ' the largest number of McNuggets that cannot be bought in exact quantity is: ', bestSoFar
scarolan (Self-grade: Pretty good)
Submitted 1 year ago | Permalink

Problem sets 2a and 2b

# This script calculates solutions to a diophantine equation with McDonalds
# Chicken McNuggets as the integer values of 6, 9, and 20.

def nuggerator(x):
    for num6p in range(0,x/6+1):
        for num9p in range(0,x/9+1):
            for num20p in range(0,x/20+1):
                n = (6 * num6p) + (9 * num9p) + (20 * num20p)
                if n == x:
                    #print (x),"McNuggets can be purchased with",(num6p),"six packs,",(num9p),"nine packs, and",(num20p),"twenty packs."
                    return True

testval = 0
count = 0

while count < 6:
    if nuggerator(testval) == True:
        count = count + 1
    else:
        count = 0
    testval = testval + 1
print "Largest number of McNuggets that cannot be bought in exact quantity:",(testval - 7)

## Problem set 2b

# Packages tuple as requested in the handout.
packages=(6,9,20)

# This is sort of a brute force hack but it works.
def nuggerator(a):
    for small in range(0,a/packages[0]+1):
        for medium in range(0,a/packages[1]+1):
            for large in range(0,a/packages[2]+1):
                n = (packages[0] * small) + (packages[1] * medium) + (packages[2] * large)
                if n == a:
                    print (a),"McNuggets can be purchased with",(small),(packages[0]),"packs,",(medium),(packages[1]),"packs, and",(large),(packages[2]),"packs."
                    return True

testval = 200
while nuggerator(testval) == True:
    testval = testval - 1
print "Given package sizes",(packages[0]),(packages[1]),"and",(packages[2]),"the largest number of McNuggets that cannot be bought in exact quantity is:",(testval)
jyen (Self-grade: Outstanding)
Submitted 1 year ago | Permalink
# Problem Set 2
# jyen
# 1 hour

# Problem 1
# 50 = 6(5) + 9(0) + 20(1)
# 51 = 6(1) + 9(5) + 20(0)
# 52 = 6(2) + 9(0) + 20(2)
# 53 = 6(1) + 9(3) + 20(1)
# 54 = 6(9) + 9(0) + 20(0)
# 55 = 6(1) + 9(1) + 20(2)
# 56 = 50 + 6(1)
# 57 = 51 + 6(1)
# 58 = 52 + 6(1)
# 59 = 53 + 6(1)
# 60 = 54 + 6(1)
# 61 = 55 + 6(1)
# 62 = 56 + 6(1)
# 63 = 57 + 6(1)
# 64 = 58 + 6(1)
# 65 = 59 + 6(1)

# Problem 2
# The theorem is true because x+5 and x+6(1) are contiguous. We can then continue indefinitely: x + (1 ...) + 6(1).   However, only when x is sufficently large so x...x+5 is contiguous.

# Problem 3

candidatenumber = 1
satisfied = 0
while satisfied <6:
    if candidatenumber%6 == 0 or candidatenumber%9 == 0 or candidatenumber%20 == 0:
        satisfied += 1
        #print "Candidate: ", candidatenumber, " is divisible by 6, 9 or 20"
    else:
        solved = 0
        c = 0
        while solved == 0 and candidatenumber > 20*c:
            a = 0
            b = 0
            while solved == 0 and candidatenumber > 9*b + 20*c:
                a = 0
                while solved == 0 and candidatenumber > 6*a + 9*b + 20*c:
                    #print candidatenumber, a, b, c
                    if (candidatenumber - (6*a) - (9*b) - (20*c))%6 == 0 or (candidatenumber - (6*a) - (9*b) - (20*c))%9 == 0 or (candidatenumber - (6*a) - (9*b) - (20*c))%20 == 0:
                        solved = 1
                        #print "Candidate: ", candidatenumber, " solved by ", a, b, c
                    a += 1
                b +=1
            c += 1
        if solved == 1:
            satisfied +=1
        else:
            satisfied = 0
            #print "Candidate: ", candidatenumber, " not solved."
    candidatenumber += 1

print "The largest number of McNuggets that cannot be bought in exact quantity is ", candidatenumber - 7

#problem 4

candidatenumber = 1
satisfied = 0
packages = (6, 9, 20)

while satisfied <6 and candidatenumber <= 200:
    if candidatenumber%packages[0] == 0 or candidatenumber%packages[1] == 0 or candidatenumber%packages[2] == 0:
        satisfied += 1
        #print "Candidate: ", candidatenumber, " is divisible by a package size"
    else:
        solved = 0
        c = 0
        while solved == 0 and candidatenumber > packages[2]*c:
            a = 0
            b = 0
            while solved == 0 and candidatenumber > packages[1]*b + packages[2]*c:
                a = 0
                while solved == 0 and candidatenumber > packages[0]*a + packages[1]*b + packages[2]*c:
                    #print candidatenumber, a, b, c
                    if (candidatenumber - (packages[0]*a) - (packages[1]*b) - (packages[2]*c))%packages[0] == 0 or (candidatenumber - (packages[0]*a) - (packages[1]*b) - (packages[2]*c))%packages[1] == 0 or (candidatenumber - (packages[0]*a) - (packages[1]*b) - (packages[2]*c))%packages[2] == 0:
                        solved = 1
                        #print "Candidate: ", candidatenumber, " solved by ", a, b, c
                    a += 1
                b +=1
            c += 1
        if solved == 1:
            satisfied +=1
        else:
            satisfied = 0
            #print "Candidate: ", candidatenumber, " not solved."
    candidatenumber += 1

if candidatenumber <= 200:
    print "The largest number of McNuggets that cannot be bought in exact quantity is ", candidatenumber - 7
else: print "No solution found - max limit reached."
hendrix (Self-grade: Pretty good)
Submitted 1 year ago | Permalink

Diophantine equations & McNuggets

Problem 1

for 50 McNuggets buy 1 pack of 20 & 5 packs of 6 (a = 5, b = 0, c = 1)

for 51 McNuggets buy 5 packs of 9 & 1 pack of 6 (a = 0, b = 5, c = 1)

for 52 McNuggets buy 2 packs of 20 & 2 packs of 6 (a = 2, b = 0, c= 2)

for 53 McNuggets buy 1 pack of 20, 1 pack of 9 & 4 packs of 6 (a = 4, b = 1, c = 1)

for 54 McNuggets buy 9 packs of 6 (a = 9, b = 0, c = 0)

for 55 McNuggets buy 2 packs of 20, 1 pack of 9 & 2 pack of 6 (a= 1, b = 2, c = 2)

Problem 2

Since we now have 6 solutions in a row it will now always be for any larger quantity to add 1 or more packs of 6 to one of these established answers.

E.G to get 56 McNuggets we add a pack of 6 to our solution for 50

to get 57 McNuggets we add a pack of 6 to our solution for 51

to get 58 McNuggets we add a pack of 6 to our solution for 52 etc

until for 61 add a pack of 6 to 55

then for 62 McNuggets add 2 packs of 6 to our solution for 50 and the same for 63, add 2 packs to our solution for 51 etc.

###
### template of code for Problem 4 of Problem Set 2, Fall 2008
###

bestSoFar = 1     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
buyable = False
packages = (6,9,20)   # variable that contains package sizes

for n in range(1, 55):   # only search for solutions up to size 200
    ## complete code here to find largest size that cannot be bought
    ## when done, your answer should be bound to bestSoFar
    print n
    for a in range (0, 55):
        for b in range (0, 55):
            for c in range (0, 55):
                if n == (packages[0] * a) + (packages[1] * b) + (packages[2] * c):
                    print n
                    buyable = True
                    break
                else:
                    buyable = False
            if buyable == True : break
        if buyable == True : break

    if buyable == False:
        bestSoFar = n

print "Largest number of McNuggets that cannot be bought in exact quantity:", bestSoFar

-------------------------------------------------------------------------

###
### template of code for Problem 4 of Problem Set 2, Fall 2008
###

bestSoFar = 1     # variable that keeps track of largest number
                  # of McNuggets that cannot be bought in exact quantity
buyable = False
packages = (7,9,20)   # variable that contains package sizes

for n in range(1, 200):   # only search for solutions up to size 200
    ## complete code here to find largest size that cannot be bought
    ## when done, your answer should be bound to bestSoFar
    print n
    for a in range (0, 200):
        for b in range (0, 200):
            for c in range (0, 200):
                if n == (packages[0] * a) + (packages[1] * b) + (packages[2] * c):
                    print n
                    buyable = True
                    break
                else:
                    buyable = False
            if buyable == True : break
        if buyable == True : break

    if buyable == False:
        bestSoFar = n

print "Largest number of McNuggets that cannot be bought in exact quantity:", bestSoFar
zpritchard (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
def mcSolver(n, packs):
    x = packs[0]
    y = packs[1]
    z = packs[2]
    for i in xrange(0,n/x+1):
        for j in xrange(0,n/y+1):
            for k in xrange(0,n/z+1):
                if i*x + j*y + k*z == n:
                    return (i, j, k)
    else: return 'No solution.'


#Problem 1
for a in xrange(50,66):
    print a,':',mcSolver(a,(6,9,20))

#Problem 2------------------------------------------------#
#The theorem is true because if six consecutive values are#
#possible to buy, the next (7th) is simply 6 more than the#
#first one, and we already know that you can buy a pack of#
#6 nuggets. Similarly, every larger number can be obtained#
#---------------------------------------------------------#

#Problem 3
mcsolved = 0
n = 0
while mcsolved < 6:
    n += 1
    N = mcSolver(n,(6,9,20))
    if N == 'No solution.':
        mcsolved = 0
    else: mcsolved += 1

print 'Largest number of McNuggets that cannot be bought in exact quantity:',n-6

#Problem 4
bestSoFar = 0
packs = (6,9,20)
for n in xrange(1,201):
    if mcSolver(n, packs) == 'No solution.':
        bestSoFar = n

print 'Given package sizes',str(packs[0])+', '+str(packs[1])+', and '+\
      str(packs[2])+',','the largest number of nuggets that cannot be bought'+\
      'in exact quantity is:',bestSoFar
danmanuk (Self-grade: Pretty good)
Submitted 2 years ago | Permalink

My solutions for 3 and 4 shown below...

# Problem 3
# Name: danmanuk


def solve(n):
    #Solve the linear equation 6a+9b+20c=n using exhaustive enumeration
    found = False
    for a in range(0,n+1):
        for b in range(0,n+1):
            for c in range(0,n+1):
                if (6*a)+(9*b)+(20*c) == n:
                    return (a,b,c)
                    found = True
    if not found:return None

count = 0

for num in range(1,100):
    if solve(num) == None:
        ans = num
        count = 0
    else:count+=1
    if count == 6:
        #This gives us an answer given that 6 is the smallest number
        #of nuggests available
        break

print 'The largest number of McNuggets that cannot be bought in exact quantity:',ans 

# Problem 4
# Name: danmanuk

def solve(n,packages):
    #function that finds answer to McNugget problem given
    #a value of n and tuple for x,y,z
    x,y,z = packages
    found = False
    for a in range(0,n+1):
        for b in range(0,n+1):
            for c in range(0,n+1):
                if (x*a)+(y*b)+(z*c) == n:
                    return True
    return None

count = 0       # coutning variable used to keep track of successes
bestSoFar = 0     # variable that keeps track of largest number of McNuggets that cannot be bought in exact quantity
packages = (6,9,20)   # variable that contains package sizes

for n in range(1, 150):
    if solve(n,packages) == None:
        bestSoFar = n
        count = 0
    else:count+=1
    if count == 6:
        break

print 'Given package sizes', packages[0], packages[1], ' and ', packages[2], ' the largest number of McNuggets that cannot be bought in exact quantity is: ',bestSoFar
mediumone (Self-grade: Could be better)
Submitted 2 years ago | Permalink

I came up with a recursive approach to solving this problem. I have posted the code for problem 3 and 4 alone. I felt that the recursive approach was more intuitive because we can keep subtracing 6 or 9 or 20 from the input number and check if the resulting number is divisible by any of these.

#
# Problem 3
#
#function isBuyable(n)
def isBuyable(n):
 #if n is divisible, return true
 if n%6==0 or n%9==0 or n%20==0:
  return True
 #if not divisible, subtract 20, 9 and 6 and
 #keep looking again recursively
 if n>20:
  return isBuyable(n-20)
  return isBuyable(n-9)
  return isBuyable(n-6)
 else:
  if n>9:
    return isBuyable(n-9)
    return isBuyable(n-6)
  else:
    if n>6:
     return isBuyable(n-6)
 #the function returns false when
 #n is less than 6
 return False
#function isBuyable(n) END

maxNotBuyable=1
sixConsecBuyableFound=False
n=1
consecBuyableCount=0

while sixConsecBuyableFound==False :
 if isBuyable(n):
  consecBuyableCount+=1
 else:
  consecBuyableCount=0
  maxNotBuyable=n
 if consecBuyableCount==6:
  sixConsecBuyableFound=True
 n+=1

print 'Largest number of Mcnuggets not buyable : ', maxNotBuyable


#
# Problem 4
#
#function isBuyable(n,x,y,z)
def isBuyable(n,x,y,z):
 if n%x==0 or n%y==0 or n%z==0:
  return True
 if n>z:
  return isBuyable(n-z,x,y,z)
  return isBuyable(n-y,x,y,z)
  return isBuyable(n-x,x,y,z)
 else:
  if n>y:
    return isBuyable(n-y,x,y,z)
    return isBuyable(n-x,x,y,z)
  else:
    if n>x:
     return isBuyable(n-x,x,y,z)
 return False
#function isBuyable(n,x,y,z) END

maxNotBuyable=1
smallNumConsecBuyableFound=False
n=1
consecBuyableCount=0
x=int(raw_input('enter x:'))
y=int(raw_input('enter y:'))
z=int(raw_input('enter z:'))
packages=(x,y,z)

while smallNumConsecBuyableFound==False :
 if isBuyable(n,packages[0],packages[1],packages[2]):
  consecBuyableCount+=1
 else:
  consecBuyableCount=0
  maxNotBuyable=n
 if consecBuyableCount==packages[0]:
  smallNumConsecBuyableFound=True
 n+=1
 if n>1000:
  maxNotBuyable='Beyond what could be bought'
  break

print 'Largest number of Mcnuggets : ', maxNotBuyable
jayd (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
#Problem Set 2a: Return the largest unsolvable diophantine equation 
#jayd

def numNuggets(nuggets):
    for numPack20 in range(0,nuggets/20+1):
        #When setting to range it this takes into account the currently selected pack of 20
        for numPack9 in range(0,((nuggets-numPack20*20)/9)+1):
            numPack6=(nuggets-20*numPack20-9*numPack9)/6
            totNuggets = 20*numPack20+9*numPack9 + 6 * numPack6
            if nuggets == totNuggets:
                return True
    return False               
#state varables
n=0
unsolvable=[]
numSolved=0
#Keep solving untill 5 are solved in a row
while numSolved <= 5:
    n+=1
    solved = numNuggets(n)
    if solved == True:
        numSolved+=1
    
    if solved == False:
        numSolved=0
        unsolvable.append(n)
    
print "Largest number of McNuggets that cannot be bought in exact quantity: %i" % unsolvable.pop()
       
#Solution = 43 




#Problem Set 2a
#jayd
#This Function solves the diophantine equation for a tuple of values ordered least to greatest.
def numNuggets(packages,nuggets):
    for large in range(0,nuggets/packages[2]+1):
        #Maximum range takes into account currently selected larger pack
        for medium in range(0,((nuggets-large*packages[2])/packages[1])+1):
            small=(nuggets-packages[2]*large-packages[1]*medium)/packages[0]
            totNuggets = packages[2]*large+packages[1]*medium + packages[0] * small
            #Return True when we find the first soltion
            if nuggets == totNuggets:
                return True
    #When all combinations have been iterated without a solution return false
    return False               

#state varables
n=0
unsolvable=[]
numSolved=0
packsize = (3,7,11)
#Keeps Solving diophantine equations until we have solved at least as many in a row as the smallest pack
while numSolved <= packsize[0]:
    noSolution=False
    n+=1
    #break if no solution found before 200
    if n >= 200:
        noSolution = True
        break
    solved = numNuggets(packsize,n)
    if solved == True:
        numSolved+=1
    
    if solved == False:
        numSolved=0
        unsolvable.append(n)    
if noSolution == False:
    print "Given package sizes %i, %i and %i the largest number of McNuggets that cannot be bought in exact quantity is: %i" % (packsize[0],packsize[1],packsize[2],unsolvable.pop())
else:
    print "Can not find a soltion less than 200"       
 
#Some results from the code
#8,9,20=39
#7,18,23=52
#3,7,11=8


   

Comments:

vilshire
1 year ago

Why is it that you add 1 in numpack20 and numpack9? The code works swimmingly I just don't understand why it works here.

    for numPack20 in range(0,nuggets/20+1):
        #When setting to range it this takes into account the currently selected pack of 20
        for numPack9 in range(0,((nuggets-numPack20*20)/9)+1):
jayd
1 year ago

vilshire,

My intention is to set a reasonable range of possible values to test. I'm rounding up the top end of my range just to make sure I don't miss a possible solution. This doesn't hurt performance much as it is just one extra test. Additionally it is more flexible than some of the solution that use a fixed range..

Sign up or log in to comment

evandavid (Self-grade: Pretty good)
Submitted 2 years ago | Permalink

This is just the answer to the final question. I have extended the functionality a wee bit, please let me know if there are any flaws. My function will take any three integers and a 'limit' and will work out whether the highest number that cannot be made with those integer factors is lower than the limit. It spits out some text to that effect.

The questions before this one were sort of self explanatory.

def calculate_combinations(x,y,z, limit=200):
    """ Calculates products less than 'limit' that can be made from three integer factors. The integer factors must be provided as arguments in ascending order, followed by the limit (optional)"""
    
    if not x < y < z:
        return "arguments must be provided in ascending order."
    
    if x == 1:
        return "You provided 1, therefore any positive integer can be made."
    
    if x % 2 == 0 and y % 2 == 0 and z % 2 == 0:
        return "You provided all even numbers, I won't bother computing that. Sorry."

    possible = []
    impossible = []
    
    i = 1
    while i <= limit + x:
        if can_be_made(i, x, y, z):
            possible.append(i)
            possible.sort()
            # print "added", i, "to possible" #debug
        else:
            impossible.append(i)
            impossible.sort()
            # print "added", i, "to impossible" #debug
        i += 1
        if len(possible) > x and possible[-1] == (possible[-x] + (x -1)):
            return "Any number greater than %s can be made. The highest number that cannot be made is %s." % (possible[-x], impossible[-1])
    
    #when i gets higher than the limit
    return "The greatest number that cannot be made is greater than the limit"

def can_be_made(n, x,y,z):
        is_possible = False
        for a in range(0, (n/x) + 1):
            for b in range(0, (n/y) + 1):
                for c in range(0, (n/z) + 1):
                    if (a * x) + (b * y) + (c * z) == n:
                        is_possible = True
        return is_possible


## samples
print "Calculating for 6,9,20:", calculate_combinations(6,9,20)
print "Calculating for 3,7,22:", calculate_combinations(3,7,22)
print "Calculating for 3,7,22:", calculate_combinations(3,7,22,10) #low limit
print "Calculating for 3,7,22:", calculate_combinations(3,7,22,11) #bounds test
print "Calculating for 2,4,6:", calculate_combinations(2,4,6)
print "Calculating for 4,3,6:", calculate_combinations(4,3,6)
print "Calculating for 20, 42, 81:", calculate_combinations(20,41,81)
print "Calculating for 20, 42, 81:", calculate_combinations(20, 42, 81, 500) #extend limit
electracool (Self-grade: Could be better)
Submitted 2 years ago | Permalink
import sys

"""
Return the combinations possbile as a list  
"""
def getNuggets(param,val):
    if not len(param) or val <= 0:
        return []
    # list 
    return [(a1,a2,a3) for a1 in range(val/param[0]+1) for a2 in range(val/param[1]+1) for a3 in range(val/param[2]+1) if (a1*param[0] + a2*param[1] + a3*param[2] == val)]
        
def getMaxNotPossible(param):
    i = count = 0 
    while i < sys.maxint:
        if len(getNuggets(param,i)) != 0: 
            count += 1 
        else: 
            count = 0
        if count == min(param): 
            break;     
        i += 1          
    if count == min(param): 
        return i-min(param)
    else: 
        return -1 
    
        
if __name__ == "__main__":
    print "Largest number of McNuggets that cannot be bought in exact quantity: " , getMaxNotPossible((6,9,20))
    print max([i for i in range(201) if len(getNuggets( (6,9,20), i )) == 0])
    print max([i for i in range(201) if len(getNuggets( (4,5,6), i )) == 0])    
    
    

Comments:

shaggorama
2 years ago

Tried your code out, got a funny result. My interpreter didn't like sys.maxint. I tried adding "from sys import *" to the top with no effect. Given that you were calling maxint to make your while look run until it reached a 'break' call, i just replaced your exit parameter with "while True." Much simpler.

Here's the output I got:

Largest number of McNuggets that cannot be bought in exact quantity: 43 43 7

def getMaxNotPossible(param):
    i = count = 0
    while True: #while i < sys.maxint:
        if len(getNuggets(param,i)) != 0:
            count += 1
        else:
            count = 0
        if count == min(param):
            break;
        i += 1
    if count == min(param):
        return i-min(param)
    else:
        return -1
shaggorama
2 years ago

Found it. Instead of "from sys import *" I should have suggested "import sys" for the dot notation you suggested. I still suggest using "while True:" instead though. Way to go on your super concise solution, by the way.

electracool
2 years ago

yup, forgot the import sys, my bad.

while True is evil, pure evil :). I once had it in production code and the break condition failed for a particular boundary condition. Had some fun :). There should be a better check than either of those, too lazy though.

Sign up or log in to comment

jspash (Self-grade: Pretty good)
Submitted 2 years ago | Permalink

Gahh! I spent two days on this and I'm sick of thinking about mcnuggets.

# Problem Set 2
# Name: jspash
# Collaborators: me
# Time:
#

# Problem #1
targets = range(50, 56)

for i in range(0, 20):
    for j in range(0, 20):
	for k in range(0, 20):
	    tmp = 6*i + 9*j + 20*k
	    if tmp in targets:
		print 'Valid:',
		print str(i) + '*6',
		print str(j) + '*9',
		print str(k) + '*20',
		print '=', tmp

#Program output:
#Valid: 0*6 6*9 0*20 = 54
#Valid: 1*6 1*9 2*20 = 55
#Valid: 1*6 3*9 1*20 = 53
#Valid: 1*6 5*9 0*20 = 51
#Valid: 2*6 0*9 2*20 = 52
#Valid: 2*6 2*9 1*20 = 50
#Valid: 3*6 4*9 0*20 = 54
#Valid: 4*6 1*9 1*20 = 53
#Valid: 4*6 3*9 0*20 = 51
#Valid: 5*6 0*9 1*20 = 50
#Valid: 6*6 2*9 0*20 = 54
#Valid: 7*6 1*9 0*20 = 51
#Valid: 9*6 0*9 0*20 = 54


# Problem #2
# Theorem: If it is possible to buy x, x+1,...,x+5 sets of McNuggets, for some x, then it is
# possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs.
#
# Solution: Since it is possible to buy x to x+5, then the next value would be covered by a box
# of 6. Then the x to x+5 sequence would start over. (Not sure how to phrase this in a math-y way!)


def can_be_bought(x):
    for i in range(0, 20):
	for j in range(0, 20):
	    for k in range(0, 20):
		tmp = 6*i + 9*j + 20*k
		if tmp == x:
#		    print 'Found for:', x
		    return True

def is_consecutive(testme):
    if list(testme) == range(testme[0], testme[-1]+1):
	return True

results = []
for n in range(1, 150):
    if not can_be_bought(n):
	# create list of totals which cannot be bought
	results.append(n)

print results
print 'Largest number of McNuggets that cannot be bought in exact quantity:', results[-1]

for x in range(0, len(results)-6):
    slice = results[x:x+6]
    if is_consecutive(slice):
	print 'Found one:', slice


# Problem Set 2
# Name: jspash
# Collaborators: me
# Time: 2:00

def can_be_bought(x, packages):
    for i in range(0, 20):
	for j in range(0, 20):
	    for k in range(0, 20):
		tmp = packages[0]*i + packages[1]*j + packages[2]*k
		if tmp == x:
#		    print 'Found for:', x
		    return True

def is_consecutive(testme):
    if list(testme) == range(testme[0], testme[-1]+1):
	return True

####
#### template of code for Problem 4 of Problem Set 2, Fall 2008
####
#
#bestSoFar = 0     # variable that keeps track of largest number
#    # of McNuggets that cannot be bought in exact quantity
#packages = (6, 9, 20)   # variable that contains package sizes
#
#for n in range(1, 150):   # only search for solutions up to size 150
#    ## complete code here to find largest size that cannot be bought
#    ## when done, your answer should be bound to bestSoFar

bestSoFar = 0
packages = (6, 9, 20)
results = []
for x in range(6, 2000):
    if not can_be_bought(x, packages):
	# create list of totals which cannot be bought
	results.append(x)

#print results

for x in range(0, len(results)-6):
    slice = results[x:x+6]
    if is_consecutive(slice):
	print 'Found it:', slice
	exit();

Comments:

yanni79
2 years ago

Good job :) I saw this in shaggorama's code above

"" if (len(placeholder) >= 6) and (placeholder[-1] - placeholder[-6] == 5 " t

to test for consecutive values, and thought it was pretty good.

Why did you use "20" as your range value? "for i in range(0, 20):"

jspash
2 years ago

Actually I should have made that number 10. The reason being...Knowing that the highest target result is 55, you would never need more than 10 boxes of 6. Therefore, you would never need more than 10 boxes of ANY size.

I upped it to 20 just in case my initial thoughts were somehow wrong.

duallain used a similar method but went to 100. His comment "this doesn't create all possible permutations, but it goes far beyond what I needed here." is pretty much what I was thinking.

Sign up or log in to comment

yanni79 (Self-grade: Could be better)
Submitted 2 years ago | Permalink

This took a while to get working. I'll be curious to see how other people tested for consecutive values.

Problem 1 (worked out manually)

55: 2c + 1a + 1b 54: 6b 53: 4a + 1b + 1c 52: 2a + 2c 51: 1a + 5b 50: 5a + 1c


56 = 50 + 6 | 50 = 5a + 1c | 6 = 1a 56 = 6a + 1c + 1a


57 = 51 + 6 | 51 = 1a + 5b | 6 = 1a 57 = 1a +5b + 1a


58 = 52 + 6 | 52 = 2a + 2c | 6 = 1a 58 = 2a + 2c + 1a


59 = 53 + 6 | 53 = 4a + 1b + 1c | 6 = 1a 59 = 4a + 1b + 1c + 1a = 5a +1b + 1c


60 = 54 + 6 | 54 = 6b | 6 = 1a

61 = 55 + 6 | 55 = 2c + 1a + 1b | 6 = 1a

62 = 50 + 12 | 50 = 5a + 1c | 12 = 2a

63 = 51 + 12 | 1a + 5b | 12 = 2a

64 = 58+ 6 | 58= 2a + 2c + 1a | 6 = 1a 64 = 2a + 2c + 1a + 1a = 4a+2c


65 = 59 + 6 | 59 = 5a +1b + 1c | 6 = 1a 65 = 6a +1b+1c

Problem 2:

Theorem: If it is possible to buy x, x+1,…, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in 6, 9 and 20 packs.

This can be shown to be true because we’ve shown how to “add” up for every integer lower than the lowest “McNugget” packet (6). We can then derive all other known digits, by adding 6 to the existing proofs. SO that x+6 is gives you x+6, x+1 +6 gives you x+7, and x+2+6 gives you x+8. Deriving all the possible digits, proves that any number (or multiple) of those digits can also be derived.

#testing for maximum n where 6a+9b+20c =! n  PROBLEM #3
impossible_Order = [0,] #collection of impossible order (aka n)
#successful impossible_Order should be (1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, etc)
possible_Order = [0, 0, 0, 0, 0, 0]
#collection of values that have a possible solution (not sure if needed)
#prepopulate the first 6 impossible values for calculation reasons
n = 1 #possible instances of numbers of McNuggets that cannot be purchased exactly
max_n = 100 #this is the biggest n we're going to try. 

max_multiplier = int(max_n / 6) #6 is the lowest "denominator" that will fit into n. 

def test_consecutive_values(): #this function will add up the last 6 numbers in possible_Order to see if we've found the solution
    sum_of_values = 0
    if possible_Order[-1] - 1 == possible_Order[-2] and possible_Order[-1] - 2 == possible_Order[-3] and possible_Order[-1] - 3 == possible_Order[-4] and possible_Order[-1] - 4 == possible_Order[-5] and possible_Order[-1] - 5 == possible_Order[-6]:
    #the if statement above tests to see if the orders are consecutive. There is probably a more elegant way of doing this
        return True
    else:
        return False
      
while n < max_n and test_consecutive_values() != True:
    for a in range(max_multiplier):
        for b in range(max_multiplier):
            for c in range(max_multiplier):
                if (6*a + 9*b +20*c == n) and possible_Order[-1] != n:
                    #the above tests n as a possible solution, and also verifies that other solutions (of a,b,c for n weren't found
                    possible_Order.append(n)                   
                    break               
    if possible_Order[-1] != n: #test to see if a possible solution to n has been found. If not, make it an impossible solution.
        impossible_Order.append(n)
    n += 1
possible_Order = possible_Order[6:] # just cleanup since this was preinitialized with six zeroes. 
print "Largest number of McNuggets that cannot be bought in exact quantity: ", impossible_Order[-1]

#the end of problem 3

#########################################
#testing for maximum n where 6a+9b+20c =! n  PROBLEM #4
bestSoFar = 0
packages = (6,9,20)
possible_Order = [0, 0, 0, 0, 0, 0]
#collection of values that have a possible solution (not sure if needed)
#prepopulate the first 6 impossible values for calculation reasons
n = 1 #possible instances of numbers of McNuggets that cannot be purchased exactly
max_n = 200 #this is the biggest n we're going to try. 

max_multiplier = int(max_n / packages[-3]) #divide by the lowest "denominator" that will fit into n. 

def test_consecutive_values(): #this function will add up the last 6 numbers in possible_Order to see if we've found the solution
    sum_of_values = 0
    if possible_Order[-1] - 1 == possible_Order[-2] and possible_Order[-1] - 2 == possible_Order[-3] and possible_Order[-1] - 3 == possible_Order[-4] and possible_Order[-1] - 4 == possible_Order[-5] and possible_Order[-1] - 5 == possible_Order[-6]:
    #the if statement above tests to see if the orders are consecutive. There is probably a more elegant way of doing this
        return True
    else:
        return False

for n in range(1, max_n):
    if test_consecutive_values() == True:
        break
    for a in range(max_multiplier):
        for b in range(max_multiplier):
            for c in range(max_multiplier):
                if (packages[-3]*a + packages[-2]*b +packages[-1]*c == n) and possible_Order[-1] != n:
                    #the above tests n as a possible solution, and also verifies that other solutions (of a,b,c for n weren't found
                    possible_Order.append(n)                   
                    break               
    if possible_Order[-1] != n: #test to see if a possible solution to n has been found. If not, make it an impossible solution.
        bestSoFar = n
possible_Order = possible_Order[6:] # just cleanup since this was preinitialized with six zeroes. 
print "Given package sizes %d, %d, and %d, the largest number of McNuggets that cannot be bought in exact quantity is: %d" % (packages[-3], packages[-2], packages[-1], bestSoFar)

#the end of problem 4


hobophobe (Self-grade: Pretty good)
Submitted 2 years ago | Permalink
def diophantine(packages=(6,9,20), maxcheck=200):
  sortpack = list(packages)
  sortpack.sort()
  if sortpack[0] <= 1: # Considering a <2pack to mean you don't want an answer
    return None
  unavailable = [1]
  check = 2
  while check < maxcheck and check - unavailable[-1] <= sortpack[0]:
    if not diophantine_test(sortpack, check):
      unavailable.append(check)
    check += 1
  return unavailable


def diophantine_test(sortpack, value):
# Check for single pack size matches
  for pack in sortpack:
    if value % pack == 0:
      return True
  if sortpack[2] > value: # Discard unusable pack size
    if sortpack[1] > value:
      return False # Single packs already checked by modulus
    else:
      return diophantine_two(sortpack[0:2], value)
  else:
    return diophantine_three(sortpack, value)
  return False


def diophantine_two(sortpack, value):
  if value % sortpack[1] == 0:
    return True
  while value >= sortpack[0]:
    if value % sortpack[0] == 0:
      return True
    value -= sortpack[1]
  return False


def diophantine_three(sortpack, value):
  while value >= sortpack[0]:
    if diophantine_two(sortpack[0:2], value):
      return True
    value -= sortpack[2]
  return False


# Part 1
# t  | 20pc | 9pc | 6pc
# 50 | 1    | 2   | 2
# 51 | 0    | 5   | 1
# 52 | 2    | 0   | 2
# 53 | 1    | 1   | 4
# 54 | 0    | 6   | 0
# 55 | 2    | 1   | 1
#
# Given the solutions above the values for 56-65 can be achieved.
# For 56-61 simply take one of the above and add an extra six-pack.
# For 62-65 simply take 56-59 and add an extra six-pack.

# Part 2
# The theorem is true because once you have covered an entire "step" of the lowest size pack
# you can simply add another of the smallest pack to achieve the next number of your choosing.
#
# Note that the same will hold for a larger pack's step-size, if achieveable. However, that
# is not strictly necessary as you will have already met the requirement for the smaller pack.

# Part 3
standard_mcdiophantine = diophantine()
print("Part 3")
print("Largest number of McNuggets that cannot be bought in exact quantity: %d" % standard_mcdiophantine[-1])

# Part 4

def vary_mcdiophantine(x,y,z):
  varied_mcdiophantine = diophantine((x,y,z))
  
  print("Given package sizes %d, %d, and %d, the largest number of McNuggets that cannot be bought in exact quantity is: %d" % (x,y,z,varied_mcdiophantine[-1]))

print("\nPart 4")
vary_mcdiophantine(3,5,7)
vary_mcdiophantine(9,4,6)
vary_mcdiophantine(3,7,11)
vary_mcdiophantine(4,11,8)
shaggorama (Self-grade: Outstanding)
Submitted 2 years ago | Permalink

Skipped problem 1: busy work. I'll come back and comment my code later (i recognize that I should probably comment as I code. I'll work on that.)

Also, I just realized I forgot to write in the escape code to break if 'guess' exceed 200 in problem 4. I'll come back and do that later, I want to try using the 'assert' function. If that doesn't work, I'll just use an if statement that returns an error.

#! /usr/bin/env python
# -*- coding: utf8 -*-
## (i'm using linux now. Much easier. For the uninitiated: the 
## above invokes python in a terminal window to interpret the 
## script file I write my code in.)

# Problem 2
## If you can buy x, x+ 1... x + 5,
## adding 6 to your previous values will get the next numbers in the sequence. 
## Therefore, if you can find solutions for 6 in a row, then you can find solutions
## for aall greater values of x.

# Problem 3

## maxval(box, guess) finds the largest feasible number
## of boxes worth trying for a given guess. This will later be 
## converted into a range. In retrospect, this function could 
## just as well have returned the range.

def maxval(box, guess):
	counter = 0
	x = 0
	while x <= guess:
		counter += 1
		x += box
	if counter > 1:	
		return counter
	else:
		return 1

## The code below "return False" is the workhorse of solving this
## problem. As the code finds solutions to the equation 6a + 9b 
## +20c, it stores them in the list 'solutions.' 
## sixconsecutive(list, value) appends the value to the list if it's ## not there already, then checks to see if there are 6 consecutive ## values in a row. If not, the function returns 'False.' If yes, the 
## function returns "True," which will return a solution below.

def sixconsecutive(placeholder, newitem):
	if newitem not in placeholder:
		placeholder.append(newitem)
	if (len(placeholder) >= 6) and (placeholder[-1] - placeholder[-6] == 5):
		return True
	else:
		return False

##initializing some variables
guess = 0
solutions = []
solution = False
while solution == False:
	guess += 1
	# generating ranges to test
	ma = maxval(6, guess)
	mb = maxval(9, guess)
	mc = maxval(20, guess)
	Arange = range(0, ma)
	Brange = range(0, mb)
	Crange = range(0, mc)
	for a in Arange:
		for b in Brange:
			for c in Crange:
				if (6*a + 9*b + 20*c) == guess:
					print guess, solutions, a, b, c
					solution = sixconsecutive(solutions, guess)				
print "Largest number of McNuggets that cannot be bought in exact quantity: ", guess - 6

# Problem 4

a = int(raw_input("a: "))
b = int(raw_input("b: "))
c = int(raw_input("c: "))
packages = (a, b, c)
smallest = min(packages)

# Used the exact same strategy from problem 3 and most of the same code. Basically, I just replaced 6, 9, and 20 with the values given by 'packages,' and replaced '6' with min(packages) where appropriate.

def maxconsecutive(placeholder, newitem):
	if newitem not in placeholder:
		placeholder.append(newitem)
	if (len(placeholder) >= smallest) and (placeholder[-1] - placeholder[-smallest] == smallest -1):
		return True
	else:
		return False

guess = 0
solutions = []
solution = False
p = packages[0]
q = packages[1]
r = packages[2]
while solution == False:
	guess += 1
	ma = maxval(p, guess)
	mb = maxval(q, guess)
	mc = maxval(r, guess)
	Arange = range(0, ma)
	Brange = range(0, mb)
	Crange = range(0, mc)
	for a in Arange:
		for b in Brange:
			for c in Crange:
				if (p*a + q*b + r*c) == guess:
					print guess, solutions, a, b, c
					solution = maxconsecutive(solutions, guess)				
print "Largest number of McNuggets that cannot be bought in exact quantity: ", guess - smallest

Comments:

yanni79
2 years ago

I liked your test for consecutive items

" if (len(placeholder) >= 6) and (placeholder[-1] - placeholder[-6] == 5 "

It was much more elegant than mine.

Sign up or log in to comment

duallain (Self-grade: Could be better)
Submitted 2 years ago | Permalink

Problem 1: Show that if you can generate a six adjacent solutions then all numbers greater than those solutions are in the answer space. Explain why this is true.

I brute forced a gigantic array. Which is terribly inefficient, if I were to do it again I would come up with a while loop to stop the process and then just append on the numbers needed past that.

Problem 2: Explain problem one in plain English.

If 50 is a solution so is 56 because one can order another 6 nugget package. If range(50,55) are solutions than so are range(56, infinity) by the same reasoning.

Problem 3: Find the largest number you cannot successfully obtain.

Brute forced this solution again. If count returned nothing then appended the number to a list. Printed out the last number in that list.

Problem 4: Write a function that takes a tuple and determines what the largest number that cannot be bought is.

combinations = []

#increment a, increment b, increment c, add those combinations 
#together, and store in list
#this doesn't create all possible permutations, but it goes far beyond 
#what I needed here.  Which was to show that if 49,50,51 can be achieved 
#then so can 52,53,54.  I choose to prove it by just generating many 
#combinations

def brute_force_nugget():
    for a in range(0,100):
            for b in range(0,100):
                    for c in range(0,100):
                            #append these combinations to a list, 			
                            combinations.append(a*6+b*9+c*20)

    #defining a new list that is an numerically ascending copy of 
    #combinations
    sort_combo = sorted(combinations)

    #define a new list, and then append non-duplicate numbers into it
    sifted_combo = []
    for i in range(0,len(sort_combo)-1):
            if sort_combo[i] != sort_combo[i+1]:
                    sifted_combo.append(sort_combo[i])


    #define a list to store the 'gaps', count returns number of instances a 
    #number appears in a list.
    store_list = []
    for i in range(0,100):
            if sifted_combo.count(i) == 0:
                    store_list.append(i)

    #trick to remember: [-1] is last entry in a list
    #finally the solution:

    print "The largest number of nuggets unable to be ordered if there are"
    print "6, 9 and 20 available is", store_list[-1]


def not_possible_to_buy(packages):
    combinations = []
        
    for a in range (0,100+min(packages)):
        for b in range (0,100 + min(packages)):
            for c in range (0,100 + min(packages)):
                combinations.append(a*packages[0]+b*packages[1]+c*packages[2])                

    sort_combo = sorted(combinations)

    sifted_combo = []

    for i in range(0,len(sort_combo)-1):
        if sort_combo[i] != sort_combo[i+1]:
            sifted_combo.append(sort_combo[i])

    store_list = []

    for i in range(0,200):
            if sifted_combo.count(i) == 0:
                    store_list.append(i)
    print "The largest number unable to be ordered for, ", packages, "is ", store_list[-1], "."

Comments:

shaggorama
2 years ago

Hey man,

Interesting method to solving the problem! Brute force is right, your code takes a few seconds to run. One small thing though: you forgot to actually call the functions you defined to generate a solution when you run the code!


Sign up or log in to comment