Q2

More on writing functions!

A

Write a function, flexible_mean, which computes the average of any number of numbers.

  • takes a variable number of floating-point arguments
  • returns 1 number: the average of all the arguments

For example, flexible_mean(1.0, 2.0) should return 1.5.

You cannot use any built-in functions.


In [ ]:


In [ ]:
import numpy as np

np.testing.assert_allclose(1.5, flexible_mean(1.0, 2.0))
np.testing.assert_allclose(0.0, flexible_mean(-100, 100))
np.testing.assert_allclose(1303.359375, flexible_mean(1, 5452, 43, 34, 40.23, 605.2, 4239.2, 12.245))

B

Write a function, make_dict, which creates a dictionary from a variable number of key / value arguments.

  • takes a variable number of key-value arguments
  • returns 1 dictionary of all the key-values given to the function

For example, make_dict(one = "two", three = "four") should return {"one": "two", "three": "four"}.

You cannot use any built-in functions.


In [ ]:


In [ ]:
assert make_dict(one = "two", three = "four") == {"one": "two", "three": "four"}
assert make_dict() == {}

C

Write a function find_all which locates all the indices of a particular element to search.

  • takes 2 arguments: a list of items, and a single element to search for in the list
  • returns 1 list: a list of indices into the input list that correspond to elements in the input list that match what we were looking for

For example, find_all([1, 2, 3, 4, 5, 2], 2) would return [1, 5].

You cannot use any built-in functions.


In [ ]:


In [ ]:
l1 = [1, 2, 3, 4, 5, 2]
s1 = 2
a1 = [1, 5]
assert set(a1) == set(find_all(l1, s1))

l2 = ["a", "random", "set", "of", "strings", "for", "an", "interesting", "strings", "problem"]
s2 = "strings"
a2 = [4, 8]
assert set(a2) == set(find_all(l2, s2))

l3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s3 = 11
a3 = []
assert set(a3) == set(find_all(l3, s3))

D

Using your answer from part C, write a function called element_counts which provides counts of very specific elements in a list.

  • takes 2 arguments: a list of your data, and a list of elements you want counted in your data
  • returns a dictionary: keys are the elements you wanted counted, and values are their counts in the data

For example, element_counts([1, 2, 3, 4, 5, 2], [2, 5]) would return {2: 2, 5: 1}, as there were two 2s in the data list, and one 5.

You cannot use any built-in functions.


In [ ]:


In [ ]:
l1 = [1, 2, 3, 4, 5, 2]
s1 = [2, 5]
a1 = {2: 2, 5: 1}
assert a1 == element_counts(l1, s1)

l2 = ["a", "random", "set", "of", "strings", "for", "an", "interesting", "strings", "problem"]
s2 = ["strings", "of", "notinthelist"]
a2 = {"strings": 2, "of": 1, "notinthelist": 0}
assert a2 == element_counts(l2, s2)