BYU logo Computer Science

Final study guide

The final will cover:

  • while loops
  • for loops
  • if/else statements
  • functions
  • strings
  • lists and nested lists
  • grids
  • dictionaries, including simple dictionaries (the values are just strings or numbers) and complex dictionaries (the values are lists or another dictionary)

To practice for the exam, print this out and take it on paper! To find the answers, download the Python notebook.

What does this print?

while

n = 0
while n < 7:
    if n % 2 == 0:
        n = n + 1
    else:
        n = n + 3
    print(n)

Answer here:

for loop

text = "And it came to pass"
result = ""
for c in text:
    if c in 'aeiou':
        result += c
    elif c.isspace():
        result += '-'
    else:
        result += c + c

print(result)

Answer here:

functions

def foo(a):
    return bar(a, a)

def bar(b, c):
    return b + c - 3

def quux(a, b):
    return foo(a) + bar(a, b)

print(quux(3, 5))

Answer here:

lists & strings

stuff = [1, 3, 5, 2, 4, 3, 0]
new_stuff = []
for item in stuff:
    if item > 3:
        new_stuff.append(str(item))
    else:
        new_stuff.append(str(item + 3))

print("-".join(new_stuff))

Answer here:

nested lists

stuff = ['foo', [], 7, [1, 2, 3], 'bar']
for thing in stuff[0]:
    print(thing)

for thing in stuff[3]:
    print(thing)

Answer here:

more lists

def shorten_words(words):
    for i in range(len(words)):
        words[i] = words[i][:2]

words = ['one', 'two', 'three']
shorten_words(words)
for word in words:
    print(word)

Answer here:

lists of lists

# remember, reversed(...) returns the items in reverse order
stuff = [[3, 2], [4, 5], [1, 0]]
for things in reversed(stuff):
    for thing in things:
        print(thing)

Answer here:

grids

from byugrid import Grid

def sums_to_7(grid, x, y):
    if not grid.in_bounds(x, y):
        return False
    result = grid.get(x, y)
    if grid.in_bounds(x+1, y):
        result += grid.get(x+1, y)
    if grid.in_bounds(x, y+1):
        result += grid.get(x, y+1)
    return result == 7

grid = Grid.build([[1, 3, 5],
                   [2, 5, 2]])

for x, y in [(0, 0), (0, 1), (2, 2), (1, 1)]:
    if sums_to_7(grid, x, y):
        print(x, y)

Answer here:

another grid

from byugrid import Grid

def in_bounds_not_none(grid, x, y):
    return grid.in_bounds(x, y) and grid.get(x, y) is not None

def has_buddies(grid, x, y):
    if not in_bounds_not_none(grid, x, y):
        return False
    buddies = 0
    for neighbor_x, neighbor_y in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
        if in_bounds_not_none(grid, neighbor_x, neighbor_y):
            buddies += 1

    return buddies >= 2


grid = Grid.build([[None, 1, None],
                   [2, 5, 7],
                   [3, None, None]])

print(has_buddies(grid, 1, 0))
print(has_buddies(grid, 1, 1))
print(has_buddies(grid, 2, 1))
print(has_buddies(grid, 3, 1))

Answer here:

dictionaries

stuff = {1: "hello", 2: "good", 0: "world"}
for i in range(len(stuff)):
    print(stuff[i])

Answer here:

meals = {'breakfast': 'cereal', 'lunch': 'apple', 'dinner': 'spaghetti' }
for key in meals.keys():
    print(key)

Answer here:

meals = {'breakfast': 'cereal', 'lunch': 'apple', 'dinner': 'spaghetti' }
for key, value in meals.items():
    print(f"{key}: {value}")

Answer here:

stuff = {'a': 'x', 'b':'y', 'c':'z'}
more = {}
for key, value in stuff.items():
    more[value] = key + key
    more[key] = value

print(more['x'])
print(more['a'])

Answer here:

def group(stuff):
    groups = {0: [], 1:[]}
    for item in stuff:
        groups[item % 2].append(item)
    return groups

groups = group([1, 3, 2, 4, 5, 6, 2, 8])
for item in groups[0]:
    print(item)

Answer here:

stuff = {
    0: {
        0: [1, 2],
        1: [3, 4]
    },
    1: {
        0: {1: 7, 0: 6},
        1: {0: 5, 1: 0}
    }
}
print(stuff[0][0][0])
print(stuff[1][1][1])
print(stuff[0][1][0])
print(stuff[1][0][1])

Answer here:

def find_vowel(word):
    for character in word:
        if character in 'aeiou':
            return character
    return None


def words_with_vowels(word_list):
    counts = {}
    for word in word_list:
        vowel = find_vowel(word)
        if vowel:
            if vowel not in counts:
                counts[vowel] = 0
            counts[vowel] += 1
    return counts

my_counts = words_with_vowels(['hello', 'who', 'is', 'this'])
print(my_counts['i'])
print(my_counts['o'])

Answer here:

lists (buggy)

The code below may have a bug. Don’t show what you think the code should have printed; show what the given code will actually print.

def capitalize(words):
    new_words = []
    for word in words:
        if word in ['should', 'be', 'bigger']:
            word = word.upper()
        new_words.append(word)
    return new_words

words = ['I','should','get','a','bigger','pizza']
capitalize(words)
for word in words:
    print(word)

Answer here:

Which input?

Which of the following inputs to the function will produce the given output?

dictionaries

def group(data):
    result = {}
    for item in data:
        key = len(item)
        if key not in result:
            result[key] = []
        result[key].append(item)
    return result

Output:

{5: ['Nephi', 'Laman', 'Zoram'], 6: ['Lemuel', 'Sariah'], 3: ['Sam'], 4: ['Lehi']}

Options:

  1. ['Sam', 'Lemuel', 'Laman', 'Nephi', 'Lehi', 'Zoram', 'Sariah']
  2. ['Sam', 'Sariah', 'Nephi', 'Lemuel', 'Laman', 'Zoram', 'Lehi']
  3. ['Nephi', 'Lemuel', 'Sam', 'Laman', 'Sariah', 'Lehi', 'Zoram']
  4. ['Nephi', 'Lemuel', 'Sam', 'Sariah', 'Lehi', 'Zoram', 'Laman']

Answer here:

Which code block?

Which code block will convert the given input to the given output?

Input: [5, 3, 6, 2, 2, 8, 1, 9, 7]

Output:{1: 25, 0: 18}

def process_A(items):
    for item in items:
        key = item % 2
        if key not in result:
            result[key] = 0
        else:
            result[key] += item
    return result

def process_B(items):
    result = {}
    for item in items:
        if item not in result:
            result[item] = 0
        else:
            result[item] += item
    return result

def process_C(items):
    result = {}
    for item in items:
        key = result % 2
        if key not in result:
            result[key] = item
        result[key] += item
    return result

def process_D(items):
    result = {}
    for item in items:
        key = item % 2
        if key not in result:
            result[key] = item
        else:
            result[key] += item
    return result

Answer here:

Which output?

Which output is the result of running the given input through the given function?

def group(data):
    result = {}
    for item in data:
        key = item[-1]
        if key not in result:
            result[key] = []
        result[key].append(item)
    return result

group(['cherry', 'apple', 'pear', 'grape', 'berry', 'pineapple'])

Input: ['cherry', 'apple', 'pear', 'grape', 'berry', 'pineapple']

Options:

  1. {'a': ['apple'], 'p': ['pear', 'pineapple'], 'g': ['grape'], 'b': ['berry'], 'c': ['cherry']}
  2. {'y': ['cherry', 'berry'], 'e': ['apple', 'grape', 'pineapple'], 'r': ['pear']}
  3. {5: ['apple', 'grape', 'berry'], 4: ['pear'], 6: ['cherry'], 9: ['pineapple']}
  4. {'e': ['apple', 'pineapple', 'grape'], 'r': ['pear'], 'y': ['berry', 'cherry']}

Answer here:

Which output?

Consider the following function:

def census_people(people):
    census_data = {}
    for person in people:
        if person.age not in census_data:
            census_data[person.age] = []
        census_data[person.age].append((person.last_name, person.first_name))
    return census_data

Which of the following is a valid return value for this function?

a.

{ 50: [('Ellis', 'John'), ('Watkins', 'Mia')],
  30: [('Peterson', 'Jack'), ('Brown', 'Lucinda')]
}

b.

{ 50: ['Ellis, John', 'Watkins, Mia'],
  30: ['Peterson, Jack', 'Brown, Lucinda']
}

c.

{ 50: {'Ellis': 'John', 'Watkins': 'Mia'},
  30: {'Peterson': 'Jack', 'Brown': 'Lucinda'}
}

d.

{ 50: {'people': [('Ellis', 'John'), ('Watkins', 'Mia')]},
  30: {'people': [('Peterson', 'Jack'), ('Brown', 'Lucinda')]},
}

Answer here:

Which doctest?

Consider this code:

def enkale(meals):
    if meals['dinner'] == 'candy':
        meals['dinner'] = 'kale'
    return meals

What doctest will fail?

a.

>>> enkale({'brunch': 'pizza', 'dinner': 'pizza', 'elevensies': 'candy', 'lunch': 'candy'})
{'brunch': 'pizza', 'dinner': 'pizza', 'elevensies': 'candy', 'lunch': 'candy'}

b.

>>> enkale({'brunch': 'pizza', 'dinner': 'candy', 'elevensies': 'candy'})
{'brunch': 'pizza', 'dinner': 'kale', 'elevensies': 'candy'}

c.

>>> enkale({'brunch': 'pizza', 'dinner': 'kale', 'lunch': 'kale', 'elevensies': 'candy'})
{'brunch': 'pizza', 'dinner': 'kale', 'lunch': 'kale', 'elevensies': 'candy'}

d.

>>> enkale({'elevensies': 'candy', 'brunch': 'pizza', 'lunch': 'candy'})
{'elevensies': 'candy', 'brunch': 'pizza', 'lunch': 'candy'}

Answer here: