cs101 ยป

# CS101 - Unit 2 Extra Practice

## Problem 1 - Weekend

# Define a procedure weekend which takes a string as its input, and
# returns the boolean True if it's 'Saturday' or 'Sunday' and False otherwise.

def weekend(day):
if day =='Saturday' or day =='Sunday':
return True
else:
return False

print weekend('Tonday')
#>>> False

print weekend('Saturday')
#>>> True

print weekend('July')
#>>> False

## Problem 2 - Stamps

# Define a procedure, stamps, which takes as its input a positive integer in
# pence and returns the number of 5p, 2p and 1p stamps (p is pence) required
# to make up that value. The answer should use as many 5p stamps as possible,
# then 2 pence stamps and finally 1p stamps.

def stamps(num):
five = num / 5
two = num % 5 / 2    # take the remainder when num is divided by 5
# divide that remainder by 2
# one = two % 2      # I think this is incorrect, as it gives the wrong result for stamps(12)
one = (num % 5) % 2  # this should be correct - the remainder of the remainder
return five, two, one

print stamps(8)
#>>> (1, 1, 1)  # one 5p stamp, one 2p stamp and one 1p stamp
print stamps(5)
#>>> (1, 0, 0)  # one 5p stamp, no 2p stamps and no 1p stamps
print stamps(29)
#>>> (5, 2, 0)  # five 5p stamps, two 2p stamps and no 1p stamp
print stamps(0)
#>>> (0, 0, 0) # no 5p stamps, no 2p stamps and no 1p stamps

## Problem 3 - Range of a set

# The range of a set of values is the maximum value minus the minimum
# value. Define a procedure, set_range, which returns the range of three input
# values.

# Hint: the procedure, biggest which you coded in this unit
# might help you with this question. You might also like to find a way to
# code it using some built in functions.

def bigger (m, n):
if m > n:
return m
return n

def biggest (a, b, c):
return bigger (a, bigger(b, c))

# it is cumbersome to do this using bigger and biggest
def set_range(p, q, r):
if p == biggest (p, q, r):
if q == bigger (q, r):
return p - r
else:
return p - q
else:
if q == bigger (q, r):
if p == bigger (p, r):
return q - r
else:
return q - p
else:
if p == bigger (p, q):
return r - q
else:
return r - p

# a much shorter way is to use built in functions
# Python has two functions max and min that return the
# biggest and smallest values of a list respectively

def set_range(p, q, r):
return max(p, q, r) - min (p, q, r)

print set_range(10, 4, 7)
#>>> 6  # since 10 - 4 = 6

print set_range(1.1, 7.4, 18.7)
#>>> 17.6 # since 18.7 - 1.1 = 17.6