Lab 8 Problems

The exercises for Lab 8 are listed below. If you did not attend lab you will need to email Allison your solutions. If email doesn't allow you to send them as attachments, upload them to Google Drive and send Allison a link.

  1. List Mystery 1

    What values that would be stored in data after the following code executes:

    data = [0] * 8
    data[0] = 3
    data[7] = -18
    data[4] = 5
    data[1] = data[0]
    x = data[4]
    data[4] = 6
    data[x] = data[0] * data[1]
  2. List Mystery 2

    What are the values of the elements in list a1 after the following code executes?

    def mystery1(a1, a2):
        for i in range(0, len(a1)): 
            a1[i] += a2[len(a2) - i - 1]
    
    def main():
        a1 = [1, 3, 5, 7, 9]
        a2 = [1, 4, 9, 16, 25]
        mystery1(a1, a2)		  
    
    main()
    
  3. List Mystery 3

    Consider the following function:

    def list_mystery3(a):
    	for i in range(1, len(a) - 1):
    		a[i] = a[i - 1] - a[i] + a[i + 1]

    What values would be stored in the list after the function list_mystery3 executes if each integer list below is passed as a parameter to it.

    1. a1 = [42, 42]
      list_mystery3(a1)
    2. a2 = [6, 2, 4]
      list_mystery3(a2)
    3. a3 = [7, 7, 3, 8, 2]
      list_mystery3(a3)
    4. a4 = [4, 2, 3, 1, 2, 5]
      list_mystery3(a4)
    5. a5 = [6, 0, -1, 3, 5, 0, -3]
      list_mystery3(a5)
    6. average

      Write a function named average that accepts a list of integers as its parameter and returns the average (arithmetic mean) of all elements in the list as a float. For example, if the list passed contains the values [1, -2, 4, -4, 9, -6, 16, -8, 25, -10], the calculated average should be 2.5. You may assume that the list contains at least one element. Your function should not modify the elements of the list.

    7. find_range

      Write a function named find_range that accepts a list of integers as a parameter and returns the range of values contained in the list, which is equal to one more than the difference between its largest and smallest element. For example, if the largest element is 17 and the smallest is 6, the range is 12. If the largest and smallest values are the same, the range is 1.

      Constraints: You may assume that the list contains at least one element (that its length is at least 1). You should not modify the contents of the list.

    8. is_sorted

      Write a function named is_sorted that accepts a list of real numbers as a parameter and returns True if the list is in sorted (nondecreasing) order and False otherwise. For example, if lists named list1 and list2 store [16.1, 12.3, 22.2, 14.4] and [1.5, 4.3, 7.0, 19.5, 25.1, 46.2] respectively, the calls is_sorted(list1) and is_sorted(list2) should return False and True respectively. Assume the list has at least one element. A one-element list is considered to be sorted.

Upcoming Due Dates