Q2

More loops, more functions, and this time with conditionals!

Part A

Write a function that tests if a number is even.

HINT: Recall the modulo operator %. This performs division on two numbers, but instead of returning their quotient, it returns the remainder of the division. For example, 7 % 3 returns 1, since the quotient is 2 with a remainder of 1.

Your function should:

  • be named is_even
  • take 1 argument, a number
  • return True if the argument is even, False otherwise

Make sure you're returning a boolean!


In [ ]:


In [ ]:
assert not is_even(3)

In [ ]:
assert not is_even(123456789)

In [ ]:
assert is_even(42)

In [ ]:
assert not is_even(42.1)

Part B

How could you test if a number is odd, using your is_even function from Part A?

Write your answer, either using 1 line of code or explaining in only 1 sentence, in the box below.

Part C

Write a function that finds the second-smallest number in a list of numbers. Your function should:

  • be named second_smallest
  • take 1 argument, a list of numbers
  • return 1 number, the second-smallest number in the list
  • throw an Exception if there are not enough elements in the list

Take note of that last point. There's a possibility, after all, that the list your function receives as input will have 1 or even 0 elements in it. How, then, do you return the second-smallest element of a 0-element list? Well, simply, you can't. So instead, you'll raise an error.

Also note: you're the one raising the error, so it's not your job to catch it! It's the job of the person using your function to note the possibility that it will throw an error, and to take appropriate action to handle it gracefully. So if your code includes any try or except statements, you're doing it wrong!

For example, second_smallest([1, 2, 3]) should return 2. Another example second_smallest([10, 100, 1000, 10000]) should return 100. And second_smallest([1]) should raise an Exception.

You cannot use any built-in sorting functions! Only range() and len().


In [ ]:


In [ ]:
import numpy as np
np.random.seed(89547)

l1 = np.random.randint(-100, 100, 100)
a1 = np.sort(l1)[1]
np.testing.assert_allclose(a1, second_smallest(l1.tolist()))

In [ ]:
np.random.seed(485)

l2 = np.random.randint(0, 1000, 100)
a2 = np.sort(l2)[1]
np.testing.assert_allclose(a2, second_smallest(l2.tolist()))

In [ ]:
try:
    second_smallest([])
except:
    assert True
else:
    assert False

In [ ]:
try:
    second_smallest([100])
except:
    assert True
else:
    assert False