Coding Exercises: Functions and Testing
1. Vampire
A person is a vampire if she is asleep during waking hours (6:00
to 22:00), or awake during sleeping hours (before 6:00 or after
22:00). Write a function is_vampire(hour, awake) where
hour is the time represented as a float
(e.g. 6.5 means 6:30), and awake represents whether the
person is awake (True or False), returning
True if that person is a vampire and False
otherwise. Most imporantly, write a unit test function and several
unit tests.
2. Good Deal
A store has marked down the prices of many items, but you only
want to buy something if the discount is more than 25% (or in other
words, the sale price is < 75% of the original price). Write a
function good_deal(originalPrice, salePrice) that
returns true if you’re getting a good deal on the item. Most
importantly, write a unit test function and several unit tests.
3. (Challenge) Prime Numbers
Write a program to print the prime numbers.
To do this, first write a function is_prime():
def is_prime(n):
{
// return True <-> n is prime
}Write a unit test function and several unit tests for this function.
Then in your program, loop through the first 100 integers and
print only the ones for which is_prime() returns
True.