Section #2 Solutions

January 24th, 2021


Written by Brahm Capoor, Juliette Woodrow, & Parth Sarin

Opening the Black Box

                    
def in_range(n, low, high):
    if n >= low and n <= high:
        return True 
    return False

def is_even(n):
    if n % 2 == 0:
        return True 
    return False

def only_one_even(num1, num2):
    if (num1 % 2 == 0 and num2 % 2 == 1) or (num1 % 2 == 1 and num2 % 2 == 0):
        return True 
    return False

def is_prime(n):
    for possible_factor in range(2, n):
        # we skip 0 and 1, since they're not the factors we're interested in 
        if n % possible_factor == 0:
            # we've found a factor of n, so n isn't prime and we can return False
            return False # ends the function
    # if the loop ends, it means we didn't find any factors
    # and so we just return True
    return True

                    
                

Playing with Strings

Remove All Occurrences

                
def remove_all_occurrences(s, to_remove):
    result = ""

    for ch in s:
        if ch != to_remove:
            result += ch

    return result
                
            

Palindrome Checker

                
def is_palindrome(s):
    for i in range(len(s)):
        if s[i] != s[len(s) - 1 - i]:
            return False
    return True
                
            

Exclaim

                
def exclaim(msg, end, n):
    """
    Prints out the message with an exclamatory
    ending which is printed n number of times.

    Arguments:
    msg -- The message to print out.
    end -- The exclamation to add to the end of the message.
    n   -- The number of times to print the exclamation.
    """
    output = msg

    for i in range(n):
        output += end

    print(output)
                
            

Grids

                
def bubble_up(grid, y):
    """
    >>> grid = Grid.build([[None, 'r', 'b'], ['b', 'b', 'b']])
    >>> bubble_up(grid, 1)
    [['b', 'r', 'b'], [None, 'b', 'b']]
    """
    # Look at every x for the given y
    for x in range(grid.width):
        if grid.get(x, y) == 'b':
            # Is the "up" square in bounds and empty?
            # (Could use in_bounds() for this)
            if y - 1 >= 0 and grid.get(x, y - 1) == None:
                grid.set(x, y - 1, 'b')
                grid.set(x, y, None)