Section #2 Solutions

Written by Juliette Woodrow, Anna Mistele, and Elyse Cornwall


Bubble Up

                    
    def can_bubble_up(grid, x, y):
        """
        >>> can_bubble_up(grid, 0, 1)
        True
        >>> can_bubble_up(grid, 0, 0)
        False
        >>> can_bubble_up(grid, 2, 1)
        False
        """
        # check if the square is a bubble
        if grid.get(x, y) != 'b':
            return False
    
        # check if the square above it is in bounds and empty
        if not grid.in_bounds(x, y-1) or grid.get(x, y-1) != None:
            return False
    
        # we know it can be bubbled up if we have made it here
        return True
                    
                
                            
    def row_has_bubble_up(grid, y):
        for x in range(grid.width):
            if can_bubble_up(grid, x, y):
                return True
        return False
                    
                

Word Guess

                
def guess_letter(in_progress_word, secret_word, guess):
    """
    Write a function that helps us play wordguess.

    The user will pass in:
    in_progress_word: what we've guessed so far in the word; unguessed letters represented by "-"
    secret_word: the word we are trying to guess
    guess: the letter we are guessing this round

    The function should return a new string that represents our in-progress word updated
    by the most recent guess. Make sure to build up a new string letter by letter!

    >>> guess_letter('------', 'python', 'o')
    '----o-'
    >>> guess_letter('--t-o-', 'python', 'p')
    'p-t-o-'
    """
    new_in_progress_word = ''

    for i in range(len(secret_word)):
        if secret_word[i] == guess:
            new_in_progress_word += secret_word[i]
        else:
            new_in_progress_word += in_progress_word[i]

    return new_in_progress_word
                
            

Exclaim

                    
    def exclaim(msg, end, n):
        """
        Returns the message with an exclamatory
        ending which is printed n number of times.
    
        Arguments:
        msg -- The message before exclaimation.
        end -- The exclamation to add to the end of the message.
        n   -- The number of times to add the exclamation.
        """
        result = msg
    
        for i in range(n):
            result += end
    
        return result
                    
                

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 longer_str(s1, s2):
    if len(s1) > len(s2):
        return s1
    return s2

def is_phone_number(s):
    if not s.isdigit():
        return False
    if len(s) != 9 and len(s) != 10:
        return False
    return True