BYU logo Computer Science

Practice Final

Try taking this practice test without looking at the answers. These questions are similar to what will be on the final.

Strings

The program just_alphas.py should take a string input and return all the lower-case letters followed by the upper-case letters.

Example

python just_alphas.py 'I study at BYU.'
studyatIBYU

python just_alphas.py 'Name: Shane Reese'
amehaneeeseNSR

For each implementation of just_alphas.py, indicate whether it is a valid implementation or not.

A

import sys


def just_alphas(text):
    lowers = []
    uppers = []
    for word in text.split():
        if word[0].islower():
            lowers.append(word)
        elif word[0].isupper():
            uppers.append(word)
    return ' '.join(lowers) + ' '.join(uppers)


if __name__ == '__main__':
    print(just_alphas(sys.argv[1]))

B

import sys


def just_alphas(text):
    lowers = ''
    uppers = ''
    for letter in text:
        if letter.islower():
            lowers += letter
        elif letter.isupper():
            uppers += letter
    return lowers + uppers


if __name__ == '__main__':
    print(just_alphas(sys.argv[1]))

C

import sys


def just_alphas(text):
    new_text = ''
    for letter in text:
        if letter.islower():
            new_text += letter
        else:
            new_text += letter.upper()
    return new_text


if __name__ == '__main__':
    print(just_alphas(sys.argv[1]))

D

import sys


def just_alphas(text):
    lowers = ''
    uppers = ''
    for word in text.split():
        for letter in word:
            if letter.isalpha():
                if letter.isupper():
                    uppers += letter
                if letter.islower():
                    lowers += letter
    return lowers + uppers


if __name__ == '__main__':
    print(just_alphas(sys.argv[1]))

replace

Write a program that replaces all ! with ? within a string.

A

import sys

def fix(text):
    new = ''
    for c in text:
        if c == '!':
            new += c
        else:
            new += '?'
    return new

if __name__ == '__main__':
    print(fix(sys.argv[1]))

B

import sys

def fix(text):
    new = ''
    for c in text:
        if c != '!':
            new += c
        else:
            new += '?'
    return new

if __name__ == '__main__':
    print(fix(sys.argv[1]))

C

import sys

def fix(text):
    new = ''
    for c in text.split():
        if c == '!':
            c = '?'
        new += c
    return new

if __name__ == '__main__':
    print(fix(sys.argv[1]))

D

import sys

def fix(text):
    return text.replace('!','?')

if __name__ == '__main__':
    print(fix(sys.argv[1]))

Words

Which program executions are possible given this code?

words.py

import sys


def strip_punct(word):
    return word.strip('.,?!')


def main(text):
    for word in text.split():
        for v in 'aeiou':
            if v in word:
                word = strip_punct(word)
        print(word)
        
        
if __name__ == '__main__':
    main(sys.argv[1])

A

python words.py 'Dr. Bean likes cheese.'
Dr.
Bean
likes
cheese

B

python words.py 'I took CS110 from Dr. Page.'
I
took
CS110
from
Dr
Page

C

python words.py Do you have chocolate?
do
you
have
chocolate

D

python words.py 'Which do you prefer: 3.1415 or apple?'
Which
do
you
prefer:
3.1415
or
apple

Files

Select each program that replaces the substring “cat” with “dog” in the input file and writes the result to the output file.

Handle both “Cat” and “cat”.

Example

python no_cats.py input.txt output.txt

input.txt

Catch that cat!

output.txt (after the program runs)

Dogch that dog!

A

import sys


def read(filename):
    with open(filename) as file:
        return file.read()
    
    
def write(outputfile, content):
    with open(filename, 'w') as file:
        file.write(content)
        
    
def main(inputfile, outputfile):
    content = read(inputfile)
    
    new_words = []
    for word in content.split():
        if 'cat' in word:
            word = 'dog'
        elif 'Cat' in word:
            word = 'Dog'
        new_words.append(word)
    
    new_content = ' '.join(new_words)
    
    write(outputfile, new_content)
    
    
if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])

B

import sys


def readlines(filename):
    with open(filename) as file:
        return file.readlines()
    
    
def writelines(outputfile, lines):
    with open(filename, 'w') as file:
        file.writelines(lines)
        

def no_cat(line):
    new_line = line.replace('cat', 'dog')
    new_line = new_line.replace('Cat', 'Dog')
    return new_line

    
def main(inputfile, outputfile):
    lines = readlines(inputfile)
    new_lines = []
    for line in lines:
        new_lines.append(no_cat(line))
    writelines(outputfile, new_lines)
    
    
if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])

C

import sys


def read(filename):
    with open(filename) as file:
        return file.read()
    
    
def write(outputfile, content):
    with open(filename, 'w') as file:
        file.write(content)
        
    
def main(inputfile, outputfile):
    content = read(inputfile)
    content = content.replace('cat', 'dog').replace('Cat', 'Dog')
    write(outputfile, content)
    
    
if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])

D

import sys


def readlines(filename):
    with open(filename) as file:
        return file.readlines()
    
    
def writelines(outputfile, lines):
    with open(filename, 'w') as file:
        file.writelines(lines)
        
    
def main(inputfile, outputfile):
    lines = readlines(inputfile)
    for line in lines:
        line.replace('Cat', 'Dog')
        line.replace('cat', 'dog')
    writelines(outputfile, lines)
    
    
if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])

zip

Which options demonstrate a possible execution of the program match.py?

match.py

import sys


def main(word1, word2):
    compared = ''
    for w1, w2 in zip(word1, word2):
        if w1 == w2:
            compared += '!'
        else:
            compared += '*'
    print(compared)
    
    
if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])

A

python match.py smith spits
!*!!*

B

python match.py banana abacus
!!*!*!

C

python match.py short shortly
!!!!!**

D

python match.py match batches
*!!!!

Mapping

Consider the following program:

subs.py

import sys

def substitute(text, substitutions): ...


def main(text):
    items = {
        "one": "1",
        "two": "2",
        "three": "3",
        "four": "4",
        "five": "5",
        "six": "6",
        "seven": "7",
        "eight": "8",
        "nine": "9",
        "ten": "10"
    }
    print(substitute(text, items))


if __name__ == '__main__':
    main(sys.argv[1])

Select all of the following implementations of substitute that can produce the following execution:

python subs.py 'Two plus two equals five! (For large values of two.)'
2 plus 2 equals 5 for large values of 2

A

def substitute(text, substitutions):
    new_text = ''
    for word in text.split():
        if word in substitutions:
            new_text += substitutions[word]
        else:
            new_text += word
    return new_text

B

def substitute(text, substitutions):
    new_words = []
    for word in text.lower().split():
        word = word.strip('.,!?()')
        if word in substitutions:
            word = substitutions[word]
        new_words.append(word)
    return ' '.join(new_words)

C

def substitute(text, substitutions):
    new_words = []
    for word in text.lower().strip('.,!?()').split():
        if word in substitutions:
            new_words.append(substitutions[word])
        else:
            new_words.append(word)
    return ' '.join(new_words)

D

def substitute(text, substitutions):
    new_words = []
    for word in text.split():
        key = word.lower().strip('.,!?()')
        if key in substitutions:
            new_words.append(substitutions[key])
        else:
            new_words.append(word)
    return ' '.join(new_words)

E

def substitute(text, substitutions):
    new_text = ''
    for word in text:
        if word in substitutions:
            new_text += substitutions[word]
        else:
            new_text += word
    return new_text

F

def substitute(text, substitutions):
    new_words = []
    for word in text.split():
        word = word.lower().strip('.,!?()')
        if word in substitutions:
            new_words.append(substitutions[word])
        else:
            new_words.append(word)
    return ' '.join(new_words)

G

def substitute(text, substitutions):
    for key, value in substitutions.lower().strip('.,!?()').items():
        text = text.replace(key, value)
    return text

Counting

Given the program:

counts.py

import sys


def count_digits(text): ...
    

def main(text):
    counts = count_digits(text)
    print(counts)
    

if __name__ == '__main__':
    main(sys.argv[1])

Which of the following implementations of count_digits can produce the following execution:

python counts.py 'The first 10 digits of Euler's Number (e) are 2.7182818285'
{0: 1, 1: 3, 2: 3, 3: 0, 4: 0, 5: 1, 6: 0, 7: 1, 8: 4, 9: 0}

A

def count_letters(text):
    counts = {}
    for i in range(0, 9):
        counts[i] = 0
    for letter in text:
        if letter.isdigit():
            counts[letter] += 1
    return counts

B

def count_digits(text):
    counts = {}
    for letter in text:
        if letter.isdigit():
            key = int(letter)
            if key not in counts:
                counts[key] = 0
            counts[key] += 1
    return counts

C

def count_digits(text):
    counts = {}
    for i in range(10):
        counts[i] = 0
    for letter in text:
        if letter.isdigit():
            counts[int(letter)] += 1
    return counts

D

def count_letters(text):
    counts = {}
    for letter in text.isdigit():
        if letter not in counts:
            counts[letter] = 0
        counts[letter] += 1    
    return counts

E

def count_letters(text):
    counts = {}
    for i in range(10):
        counts[i] = 0
    for letter in text:
        if letter.isdigit() not in counts:
            counts[letter] = 0
        counts[letter] += 1    
    return counts

Grouping

Given the following program:

group_words.py

import sys


def make_groups(text): ...
    
    
def main(text):
    groups = make_groups(text)
    print(groups)


if __name__ == '__main__':
    main(sys.argv[1])

Which implementations of make_groups can produce the following output?

python group_words.py 'Even these eat seven cheeses and sneeze'
{2: ['even', 'these', 'seven'],
 1: ['eat'],
 3: ['cheeses', 'sneeze'],
 0: ['and']}

A

def make_groups(text):
    groups = {}
    for word in text.lower().split():
        key = 0
        for letter in word:
            if letter == 'e':
                key += 1
        
        if key not in groups:
            groups[key] = []
        
        groups[key].append(word)
    return groups

B

def make_groups(text):
    groups = {}
    for word in text.split():
        key = 0
        for letter in word:
            if letter.lower() == 'e':
                key += 1
        
        if key not in groups:
            groups[key] = [word.lower()]
        else:
            groups[key].append(word.lower())
    return groups

C

def make_groups(text):
    groups = {}
    for word in text:
        key = len(word)
        
        if key not in groups:
            groups[key] = [word]
        else:
            groups[key].append(word)
    return groups

D

def make_groups(text):
    groups = {}
    for word in text.split():
        new_word = ''
        for letter in word:
            if letter.lower() == 'e':
                new_word += letter
        
        key = len(new_word)
        
        if key not in groups:
            groups[key] = []
        
        groups[key].append(word.lower())
    return groups

To Consider 🤔

Which code blocks are easier to identify as valid or invalid?

What qualities or patterns do the easier blocks have in common?

If you want to write code that makes it easy to determine whether it does the right thing or not, which code blocks do you want to model after?

Go, and do thou likewise.