Q4

Writing functions!

A

Write a function that computes the cube of a number.

  • named cube
  • takes 1 argument, a number
  • returns 1 number, the cube (third power) of the argument

In [ ]:


In [ ]:
import numpy as np
np.testing.assert_allclose(27.0, cube(3.0))
np.testing.assert_allclose(125.0, cube(5.0))
np.testing.assert_allclose(1000.0, cube(10.0))

B

Write a function that computes the remainder of two numbers.

  • named remainder
  • takes 2 arguments, two numbers x and y
  • returns 1 number, the remainder of x (the first argument) divided by y (the second argument)

In [ ]:


In [ ]:
import numpy as np
np.testing.assert_allclose(0.0, remainder(100, 2))
np.testing.assert_allclose(6.0, remainder(123, 39))
np.testing.assert_allclose(3.0, remainder(987, 4))

C

Write a function that tests if a number is even.

  • named is_even
  • takes 1 argument, a number
  • returns True if the argument is even, False otherwise

In [ ]:


In [ ]:
assert not is_even(3)
assert not is_even(123456789)
assert is_even(42)

D

Write a function that adds a certain amount (a number) to every element in a list.

  • named add_to_list
  • takes 2 arguments: the list, numbers, and the number, to_add, to add to every element in numbers
  • returns a list: the new list that contains the added elements

In [ ]:


In [ ]:
import numpy as np
assert 3 == len(add_to_list([1, 2, 3], 5))
np.testing.assert_allclose([6, 7, 8], add_to_list([1, 2, 3], 5))
np.testing.assert_allclose([866.7, 18.75, 35.9356, 12.5], add_to_list([854.2, 6.25, 23.4356, 0.0], 12.5))

E

Write a function that finds the minimum value in a list of numbers.

  • named minimum
  • takes 1 argument, a list of numbers
  • returns 1 number, the smallest number in the list

In [ ]:


In [ ]:
assert 5 == minimum([10, 15, 5, 20])
assert 100 == minimum([100, 200, 300, 400, 500])
assert 42 == minimum([96456, 454, 2342, 234, 647, 67, 42])