Q3

In this question, we'll focus on looping.

Part A

In the question below, you'll write code that generates a new list, reverse, that is the same as the input list except with its elements backwards relative to the original.

As an example, if the input list is [1, 2, 3], the output list reverse should be [3, 2, 1].


In [ ]:
def reverse_list(inlist):
    reverse = []

    ### BEGIN SOLUTION
    
    ### END SOLUTION
    
    return reverse

In [ ]:
t1 = [1, 2, 3]
t2 = [3, 2, 1]
assert set(t2) == set(reverse_list(t1))

In [ ]:
t1 = [2, 6, 52, 64, 3.4, "something", 3, 6.2]
t2 = [6.2, 3, "something", 3.4, 64, 52, 6, 2]
assert set(t1) == set(reverse_list(t2))

Part B

This time, you'll implement a method for computing the average value of a list of numbers. Remember how to compute an average: add up all the values, then divide that sum by the number of values you initially added together.

Example Input: [2, 1, 4, 3]

Example Output: 2.5

Aside from len(), you cannot use built-in functions like sum() or import any packages to help you out. You have to write this on your own!


In [ ]:
def average(numbers):
    avg_val = 0.0
    
    ### BEGIN SOLUTION
    
    ### END SOLUTION
    
    return avg_val

In [ ]:
import numpy as np

inlist = np.random.randint(10, 100, 10).tolist()
np.testing.assert_allclose(average(inlist), np.mean(inlist))

In [ ]:
inlist = np.random.randint(10, 1000, 10).tolist()
np.testing.assert_allclose(average(inlist), np.mean(inlist))

Part C

In this question, the function below first_negative takes a list of numbers (creatively-named numbers). Your goal is to write a while loop that searches for the first negative number in the list.

You should set the variable num equal to that negative number.


In [ ]:
def first_negative(numbers):
    num = 0
    
    ### BEGIN SOLUTION
    
    ### END SOLUTION
    
    return num

In [ ]:
import numpy as np

np.random.seed(59859)
inlist1 = (np.random.randint(10, 100, 10) - 50).tolist()
a1 = -22
assert a1 == first_negative(inlist1)

In [ ]:
np.random.seed(1237)
inlist2 = (np.random.randint(10, 100, 10) - 50).tolist()
a2 = -29
assert a2 == first_negative(inlist2)