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:
is_even
True
if the argument is even, False
otherwiseMake 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)
Write a function that finds the second-smallest number in a list of numbers. Your function should:
second_smallest
Exception
if there are not enough elements in the listTake 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