MIT OpenCourseWare 6.00 Introduction to Computer Science and Programming: Lesson 3, HW 1
# 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
baggedlunch
1 year ago