Cleaver Karel

Jed Rembold & Fred Agbo

January 24, 2024

Announcements

  • Problem Set 1 is due on Monday Jan. 29th @ 10pm!
    • You’ll have basically all you need to solve it after today
  • Small sections starting up today or tomorrow (depending on when your section meets)
    • Did you not get a message from Prof. Jed about your section meeting time? You must not have filled out the availability poll.
    • Come see me after class and we can see about getting you placed into one.
  • Polling: https://www.polleverywhere.com/agbofred203
    • Reminder: include enough of your name that I can uniquely identify you!
  • Welcome to TechByte event tomorrow by 11:30 am @ Ford 102. Talk will be on how to find and apply for internships
  • Welcome to Cookie Social at QUAD Center (Ford 224) TUE Jan 30 @ 4:30pm
  • I’ve requested for relocation of lecture hall. Stay tunned for the info soon!

If Conditions

  • Predicate functions can be used to control a kind of “switch”: running one piece of code if the answer is yes and a different piece of code if the answer is no.

  • Commonly called if or if-else statements, they take on the syntax of:

    if conditional_test:
        # Code to run if test answer is yes
    else:
        # Code to run if test answer is no
  • If you don’t want the code to do anything special if the answer is no, you can ignore the “else” part of the statement:

    if conditional_test:
        # Code to run if test is true
    # Carrying on with code that will always run

Remember Predicate Functions?

Potential questions you can ask Karel include:

front_is_clear() front_is_blocked()
left_is_clear() left_is_blocked()
right_is_clear() right_is_blocked()
beepers_present() no_beepers_present()
beepers_in_bag() no_beepers_in_bag()
facing_north() not_facing_north()
facing_south() not_facing_south()
facing_east() not_facing_east()
facing_west() not_facing_west()

Iterative: while

  • Another common use of predicate functions is in controlling a type of iterative function called a while loop

  • The structure of a while loop looks like:

    while some_conditional_test:
        # Code to repeat as long as the answer
        # to the conditional_test is yes (true)
    # Code to run once the answer is no
  • All of our predicate functions give yes-or-no answers though! So we can do something like

    while front_is_clear():
        move()

    which will continually move Karel forward as long as there is not a wall in front of them!

Smarty Karel

  • Combining conditional statements with loops lets us write a program for Karel in which it can react to different situations in different ways, all using the same code
  • Our pothole code from earlier could only handle two potholes, and they had to be perfectly spaced
  • With one loop and one if statement, we can make the program fill any number of potholes with any manner of spacing!
  • Key questions:
    • How do we know when we are done?
    • How do we know when we reach a pothole?

Smart Potholes

def main():
    """
    Main function to fill any number of
    potholes at any location!
    """
    while front_is_clear():
        if right_is_clear():
            fill_pothole()
        move()

def fill_pothole():
    """
    Fills a single pothole and returns 
    to where it started. 
    """
    turn_right()
    move()
    put_beeper() #assuming infinite beepers available
    turn_around()
    move()
    turn_right()

def turn_right():
    """ Turns Karel 90 deg to the right. """
    turn_left()
    turn_left()
    turn_left()

def turn_around():
    """ Turns Karel 180 deg around. """
    turn_left()
    turn_left()

Inception: Loops in Loops

  • Whenever a loop ends, you just return to the same indentation level as when that loop began

  • For loops inside other loops then, this means that the “inner-most” loop runs from start to finish for every step of the outer loop

    while front_is_clear():
        move()
        while not_facing_north():
            turn_left()
        turn_left()
    put_beeper()

Understanding Check

Karel starts as shown to the right with 20 beepers in its bag. After executing the commands below, how many beepers are left in the bag upon the conclusion of the program?

while left_is_clear():
    while front_is_clear():
        move()
        if no_beepers_present():
            put_beeper()
    turn_left()

  1. 12
  2. 13
  3. 15
  4. 19

Counting Loops

  • Sometimes we know the number of times we want to loop

    • It is not dependent on some condition like a while loop
  • In these circumstances, the iterative statement called a for loop is best used

  • Syntax looks like:

    for i in range(desired_count):
        # statements to be repeated
    • desired_count is an integer indicating the number of times you want the loop to repeat
    • The i is a name that we will later make more general, but for now you can always leave it as an i

An Example for you

  • Suppose we want Karel to create a 6x6 square outline of beepers in a room
  • Need to repeat making each side 4 times
  • Need to repeat placing a beeper and moving 6 times for each side
    • Placing 6 beepers requires moving only 5 times. So not everything can be in the loop

A Potential Solution

import karel

def main():
    """Draw a 4x4 square in the world."""
    position()
    draw_box()

def position():
    """Move to starting corner of box."""
    move()
    move()
    turn_left()
    move()
    move()
    turn_right()

def turn_right():
    """Turns Karel 90 deg to the right."""
    turn_left()
    turn_left()
    turn_left()

def draw_box():
    """Draws a box with 4 equal sides in a CCW direction."""
    for i in range(4):
        draw_6_line()
        turn_left()

def draw_6_line():
    """Draws a straight line of 6 beepers, if space."""
    for i in range(5):
        if no_beepers_present():
            put_beeper()
        if front_is_clear():
            move()
    if no_beepers_present(): # Last beeper to make 6
        put_beeper()

Summary So Far

  • Karel can only:
    • move()
    • turn_left()
    • pick_beeper()
    • put_beeper()
  • Can get info about surroundings using predicate functions
    • Eg. front_is_clear()
  • Group code into bundles

    def function_name():
        # Code to be grouped
  • Conditional statements
    • Run certain code blocks only if a condition is true

      if condition_test:
          # Code if answer yes
      else:
          # Code if answer no
  • Iterative statements
    • while loop: repeat code block as long as condition is true

      while condition_test:
          # Code to repeat
    • for loop: repeat set number of times

      for i in range(desired_count):
          # Code to repeat

Algorithms

  • The process of designing a solution strategy to a problem is called algorithmic design
  • An algorithm is just an approach or recipe for a method to solve a particular problem
    • Frequently language agnostic
  • Algorithms are not a new concept
    • Euclids algorithm to find greatest common denominators for instance
  • A large part of computer science is focused on the study or analysis of algorithms

Algorithm ⮕ Code

  • You need to have an algorithm in place before you can write the code to tell the computer what you want to do
    • Imagine an alien asking me how to bake a cake. I need to understand the steps to baking the cake before I can even worry about the translation or communication
  • Programming tools like conditional statements and loops will frequently play a role in your algorithm, but as general concepts
    • I can easily describe a loop to you without needing the exact syntax of Python
  • The implementation of the algorithm is the act of translating it into Python (or whatever language you are using)

An Amazing Algorithm

  • Consider a simple, loop-less, maze that we want to move through
    • Karel could start anywhere
    • The end of the maze is a beeper
  • A common algorithm to get through the maze is to essentially always follow or touch the wall to your right
    • How could we phrase this in language Karel would understand?
  • Let’s take a few minutes to work with a neighbor(s) to sketch out your code

An Amazing Algorithm

  • Practically speaking, this largely means to go forward unless a passage opens to your right, in which case you take that passage
  • In Karel, since the exit is a beeper, we might implement the above algorithm as:
while no_beepers_present():
    # if opening on right, we follow
    if right_is_clear():
        turn_right()
        move()
    else:
        # go forward if possible or turn
        if front_is_clear():
            move()
        else:
            turn_left()
// reveal.js plugins