Practice Midterm Exam Solution


Problem 1: Border Karel

from karel.stanfordkarel import *

def next_position():
    # Assumes Karel is facing a wall at the end of line of placed
    # beepers and repositions Karel to be facing in direction of next
    # line in the border of beepers that needs to be placed
    turn_right()
    move()
    turn_right()
    move()
    turn_right()

def handle_border():
    # Assumes Karel starts one avenue before the first beeper to
    # be placed in this line of the border.  Places beepers until
    # Karel reaches a wall, but does not place a beeper on the last
    # corner (where Karel is facing the wall).
    move()
    while front_is_clear():
        # We check for any existing beepers, so we don't put
        # two beepers on any of the "corners" of the border
        if no_beepers_present():
            put_beeper()
        move()

def move_up_row():
    # Moves Karel up one row while keeping the same orientation
    turn_left()
    move()
    turn_right()

def turn_right():
    # Karel turns to the right of the direction it is originally facing
    for i in range(3):
        turn_left()

def main():
    move_up_row()
    for i in range(4):
        handle_border()
        next_position()

if __name__ == "__main__":
    run_karel_program()

Problem 2: Largest and Second Largest

SENTINEL = 0    # the sentinel used to signal the end of the input

def main():
    largest = -1
    second_largest = -1
    while True:
        value = int(input("Enter value: "))
        if value == SENTINEL:
            break
        if value > largest:
            second_largest = largest
            largest = value
        elif value > second_largest:
            second_largest = value

    print(f"The largest value is {largest}")
    print(f"The second largest value is {second_largest}")


# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == "__main__":
    main()

Problem 3: Collapse List

def collapse(nums):
    result = []
    for i in range(len(nums) // 2):

        # Since we're going one pair at a time, we only need
        # to go as many as times as half the number of elements
        result.append(nums[i * 2] + nums[i * 2 + 1])
  
    if len(nums) % 2 == 1:
        result.append(nums[-1])

    return result

Problem 4: Longest Consonants

def longest_consonants(s):
    best_count = 0
    count = 0

    for char in s:
        if char.isalpha() and char not in "aeiou":
            count += 1
            if count > best_count:
                best_count = count
        else:
        	# Found a vowel or non-alpha character.
        	# Reset back to zero.
            count = 0

    return best_count

Problem 5: Make True Grid

def max_cols(grid):
    """
    This function returns maximum number of columns across 
    all rows of grid.
    """
    max_elems = 0  # Keep track of maximum row size 

    for i in range(len(grid)):
        num_elems = len(grid[i])
        if num_elems > max_elems:  # If this row has more elements, 
            max_elems = num_elems  # update the maximum row size found.

    return max_elems

def make_true_grid(grid, row_size, filler):
    """
    This function makes the grid passed in a true grid by padding rows 
    with the filler element to make sure they are all the same size.
    """

    # If the grid has a row with more elements than row_size, update 
    # row_size to be that number of elements, making all rows as large
    # as largest row.  Otherwise, row_size will be unchanged.    
    cols = max_cols(grid)  

    if cols > row_size:        
        row_size = cols    

    # Pad rows with extra filler elements, making all rows same length
    for i in range(len(grid)):        
        cols = len(grid[i])        
        for j in range(row_size - cols):            
            grid[i].append(filler)