Practice Midterm Solutions
Exam Solutions
Problem 1: Karel the Robot (20 points)
"""
File: BorderKarel.py
This Karel program creates an inside border around the world.
"""
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: Full program (25 points)
"""
File: secondlargest.py
"""
SENTINEL = 0 # the sentinel used to signal the end of the input
def main():
print('This program finds the two largest integers entered by')
print('the user. Enter values, one per line, using a ' + str(SENTINEL))
print('to signal the end of the input.')
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('The largest value is ' + str(largest))
print('The second largest is ' + str(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: Lists of lists (25 points)**
def diagonal_line(grid):
row1 = 0 # Used to store row of 1 in initial grid
col1 = 0 # Used to store column of 1 in initial grid
# Find the 1 in the initial grid. Keep track of position in col1, row1
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == 1:
row1 = row
col1 = col
# Generate the diagonal line of 1's by iterating through the rows of the
# grid and adding 1's on the diagonal line (making sure not to go off the
# ends of the grid.
for row in range(len(grid)):
# Determine column for new 1 based on row and col1, row1
col = col1 - row1 + row
if col >= 0 and col < len(grid[0]): # Make sure we don't go off the grid
grid[row][col] = 1
Problem 4: Images (30 points)
def set_blurred_pixel(img, blur, x, y):
num_pixels = 0 # Keep track of number of pixels we are averaging over
red = 0 # Used to determine average red value
green = 0 # Used to determine average green value
blue = 0 # Used to determine average blue value
# Loop over all the "neighbors" of the pixel at location (x, y)
for row in range(y - 1, y + 2): # loop over y values of neighbor pixels
for col in range(x - 1, x + 2): # loop over x values of neighbor pixels
# Make sure the neighboring pixel we try to get is not off the image
if row >= 0 and row < img.height and col >= 0 and col < img.width:
num_pixels += 1
# Recall that row is the y value and col is the x value
red += img.get_pixel(col, row).red
green += img.get_pixel(col, row).green
blue += img.get_pixel(col, row).blue
# Set pixel in blurred image to be average of red, green, and blue values,
# respectively, from pixels in neighborhood of pixel in the original image
pixel = blur.get_pixel(x, y)
pixel.red = red // num_pixels
pixel.green = green // num_pixels
pixel.blue = blue // num_pixels
def create_blurred_image(img):
width = img.width
height = img.height
# Create a new blank image that will be set to be the blurred image
blur = SimpleImage.blank(width, height)
for y in range(height):
for x in range(width):
# Set blurred pixel at location (x, y)
set_blurred_pixel(img, blur, x, y)
return blur # return the blurred image
Problem 5: Strings (20 points)
def remove_doubled_letters(str):
"""
Removes any doubled letters from a string.
"""
result = ""
for i in range(len(str)):
ch = str[i]
if (i == 0) or (ch != str[i - 1]):
result += ch
return result