Overview

The final exam is comprehensive and will cover the following topics:

Before Midterm

  1. Basic Syntax & Types

  2. Conditional Execution

  3. Iteration

  4. Functions

  5. Lists, Strings

  6. Dictionaries, Sets

After Midterm

  1. File I/O

  2. Data Manipulation

  3. Image Processing

  4. Artificial Intelligence

  5. Web Programming

Comprehensive Final Exam

Although the final exam is comprehensive, it will mainly focus on the second half of the semester.

As with the quizzes, the exam will consist of definitions, short answers, code evaluation, debugging, and programming sections. For the programming section, you will be able to use your computer (but only after you have completed all the other sections).

Below are examples of the type of questions that may be asked on the exam. It is meant to be representative, rather than exhaustive (ie. there may be questions that show up on the exam that are not shown below).

Definitions

Briefly define the following terms.

Before Midterm

  1. Program:

  2. Interpreter:

  3. Variable:

  4. Syntax Error:

  5. Expression:

  6. Statement:

  7. Boolean Expression:

  8. Exception:

  9. Short Circuit Evaluation:

  10. Infinite Loop:

  11. Immutable:

  12. Function:

  13. Named Argument:

  14. Scope:

  15. KeyError:

  16. IndexError:

After Midterm

  1. File Handle

  2. Text File

  3. Binary File

  4. CSV

  5. JSON

  6. IOError

  7. Image

  8. Color

  9. Pixel

  10. Bot

  11. URL

  12. IP Address

  13. Port

  14. HTTP

Short Answer

  1. What is the difference between a while loop and a for loop? Give two examples where we would prefer one over the other.

  2. What is the difference between a fruitful function and a void function? How do we make a function fruitful? How would you utilize the outputs of a fruitful function?

  3. What is the difference between a list and a string? What can you do with a list that you can't do with a string and vice versa?

  4. What is the difference between a global variable and a local variable? Give an example of each.

  5. What is the difference between a list, a dict, and a set? For each data structure, identify a use case for which it is best suited for.

  6. Write some Python code that does each of the following:

    1. Reads all the contents of a file into a single string.

    2. Reads all the contents of a file into a list of strings.

    3. Prints out the contents of a file line-by-line.

    4. Lists the contents of a directory.

    5. Write all the items in a list of strings to a file.

    6. Write all the items in a dictionary to a file.

  7. What are the four basic operations you can perform on a file (handle)?

  8. Why should you close a file after opening it?

  9. What are some reasons why an open would fail?

  10. What are some advantages to using the csv Python module for parsing comma-separated-values, rather than simplying doing str.split?

  11. Describe how an image is represented in a computer program? What exactly is a pixel?

  12. Describe what exactly is a chat bot. How does it work?

  13. Describe what exactly is a game playing bot. How does it work?

  14. What are the components of a URL? Given the URL, http://127.0.0.1:9123/files?name=echosmith.mp3, identify each component.

  15. In the context of HTTP, what is a client and what is a server? What is each side responsible for in a HTTP transaction?

Code Evaluation

  1. What is the result of the each of the following lines of Python code:

    print type(1 + 3)
    print type(1 + 3.0)
    print '1' + 3
    print '1' + '3'
    
  2. What is the result of the following Python code:

    x = 1
    y = 2
    z = x + y
    print x, y, z
    x = y
    y = x
    print x, y, z
    
  3. What is the result of the following Python code:

    for i in range(0, 10):
        if i < 4:
            continue
        elif i == 7:
            break
        else:
            print i
    print i
    
  4. What is the result of the following Python code:

    def pretty_print_string(s, title=False, sort=False):
        if title:
            s = s.title()
        if sort:
            s = ' '.join(sorted(s.split()))
    
        print s
    
    pretty_print_string('python is the best')
    pretty_print_string('python is the best', sort=True)
    pretty_print_string('python is the best', True, True)
    
  5. What is the result of the following Python code:

    def filter_numbers(numbers, n):
        results = []
        for number in numbers:
            if not number % n:
                results.append(number)
        return results
    
    for i, v in enumerate(filter_numbers(range(0, 10), 4)):
        print i, v
    
  6. What is the result of the following Python code:

    def search(numbers):
        is_found = False
        index    = 0
    
        while index < len(numbers) and not is_found:
            if not numbers[index] % 2 and not numbers[index] % 3:
                is_found = True
            else:
                index += 1
    
        return index, numbers[index]
    
    print search(range(3, 9))
    print search(range(8, 16))
    
  7. What is the result of the following Python code:

    d = {}
    s = 'banana band'
    t = ''.join(s.split())
    
    for l in t:
        d[l] = d.get(l, 0) + 1
    
    for k in sorted(d, key=d.get, reverse=True):
        print d[k], k
    
  8. What is the result of the following Python code:

    d = {'boy': 'garcon', 'girl': 'fille'}
    
    print d['boy']
    print d['fille']
    print d.get('man')
    print d.get('man', d.get('boy'))
    
  9. Given the following turtles.csv file:

    Name,Color,Weapon,Species
    Leonardo,blue,katana,turtle
    Donatello,purple,bo,turtle
    Raphael,red,sai,turtle
    Michelangelo,orange,nunchucks,turtle
    Splinter,brown,staff,rat
    Casey Jones,white,hockey stick,human
    April O'Neil,yellow,microphone,human
    Shredder,purple,armor,human
    

    What is the result of the following Python code:

    c = {}
    for index, line in enumerate(open('turtles.csv')):
        if not index:
            continue
    
        d = line.strip().split(',')
        s = d[-1]
    
        c[s] = c.get(s, 0) + 1
    
    for k, v in sorted(c.items()):
        print '{:8}: {}'.format(k, v)
    

Translation

  1. Convert the following Python code to use a while loop instead of a for loop:

    numbers = [5, 4, 7, 0, 1]
    count   = 0
    
    for number in numbers:
        if number:
            break
        count += 1
    
  2. Search: Convert the search function above to use a for loop and to take an additional argument find_all which by default is set to False. If find_all is True then the search function should return a list of all numbers that match the criteria.

  3. Given the turtles.csv files and code above, modify the code to use the csv module instead of manually parsing the csv data.

Debugging

  1. Correct the following Python code:

    volume of sphere = (4/3) math.pi (r^3)
    print volume of sphere
    
  2. The Python code below is suppose to count all of the even numbers between 1 and 100 (inclusive) that are also a multiple of 5, but it contains some errors. Identify and fix the errors:

    while i < 100:
        if i % 2 or i % 5:
            total + 1
    print total
    
  3. The Python code below is suppose to determine if the given list of numbers is sorted. That is, it should return True if each item in the list is less than the next item. Unfortunately, there are a few errors in the code below. Identify the errors and fix the code.

    def is_sorted(numbers):
        ''' Return whether or not the list of numbers is sorted '''
        for i in numbers:
            if numbers[i] < numbers[i + 1]:
                print 'True'
            else:
                print 'False'
    
  4. The Python code below is suppose to use a dict to determine the most frequenctly used word in a string of text, but it contains some errors. Identify and fix the errors:

    def most_frequent_word(text):
        counts = {}
        for word in text:
            counts[word] = counts[word] + 1
    
        most = 0
        for key, value in enumerate(counts):
            if value < counts[most]:
                most = value
        return most
    

Programming

  1. Write Python code that requests the base and height of a triangle from the user, computes the area of a triangle, and then prints the result:

    Base? 4
    Height? 2
    The area of a triangle with base 4 and height 2 is 4.
    
  2. Given a list of random integers, numbers, write Python code that computes the sum of all the numbers between a and b (inclusive) and prints the resulting total.

  3. Write Python code that prints 'Yeah' if a number n is between the values a and b (inclusive). Otherwise, print 'Nope'.

  4. Write Python code that generates n random numbers (between 0 and 9), counts the number of odd and even numbers, and then prints out the totals.

  5. Write Python code that computes the list of the even numbers between 0 and 100. that are also a multiple of 7.

  6. Write Python code that simulates rolling a die until we a 6 and reports how many rolls it took.

  7. Write a Python function called read_password:

    def read_password(password, prompt='Password?', max_attempts=3):
        ''' Returns whether or not user has entered the correct password. '''
    

    This function provides the user with the prompt and reads the input from the user. This input is checked against the password. If the user input and the password match, then True is returned. This is attempted max_attempts times and then False is returned if there is no match.

  8. Write a Python function called filter_range:

    def filter_range(numbers, a, b):
        ''' Return all numbers between a and b (inclusive) '''
    
    >>> filter_range([7, 1, 5], 0, 5)
    [1, 5]
    

    Given a list numbers and two integers a and b, return a list of all items in numbers that are between a and b (inclusive).

  9. Write a Python function called count_word:

    def count_word(text, word, case_sensitive=False):
        ''' Return number of times word appears in text '''
    
    >>> count_word('Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo', 'buffalo')
    8
    
    >>> count_word('Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo', 'buffalo', True)
    5
    

    Given a string text and a string word, this function returns the number of times word appears in text. If case_sensitive is True, then letter case must be factored in comparing strings.

  10. Write a function, translate_shorthand, that replaces shorthand such as "ttyl" with "talk to you later":

    def translate_shorthand(text):
        ''' Return translated text by substituting words found in the
        dictionary with the associated values '''
    
  11. Write a Python program that lets you look up a value in a CSV file by row number and column name.

    def lookup_csv_value(csv_path, row_number, column_name):
        ''' Return the value in the file `csv_path` at the `row_number` for
        the column `column_name`.
        '''
    
    # Examples using 'turtles.csv' file above
    >>> lookup_csv_value('turtles.csv', 0, 'Name')
    'Leonardo'
    
    >>> lookup_csv_value('turtles.csv', 3, 'Weapon')
    'nunchucks'
    
  12. Given the following URL:

    http://xavier.h4x0r.space:9097/services.json
    

    Using requests to fetch the JSON data and examine the data to count all the different opsys values from the services listed in the catalog:

    def count_opsys(url):
        ''' Return a dictionary containing the counts of all the different
        `opsys` in the JSON data '''
    
    >>> count_opsys('http://xavier.h4x0r.space:9097/services.json')
    {u'Linux': 4}
    

    Note: If the URL above does not work, try http://www3.nd.edu/~pbui/teaching/cdt.30010.fa16/static/json/services.json.

  13. Write a Python function that determines if a color is found in an image.

  14. Write a Python function that returns the total number of different colors in an image.

  15. Write a Python function that copies an image to a new image.