Section #2 Solutions

January 16th, 2022


Written by Juliette Woodrow and Anna Mistele


Playing with Strings

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)
                
            

Word Guess Helper

                
def wordguess_helper(guessed_word, secret_word, guess):
    new_guessed_word = ""
    for i in range(len(secret_word)):
        if secret_word[i] == guess:
            new_guessed_word += secret_word[i]
        else:
            new_guessed_word += guessed_word[i]
    return new_guessed_word
                
            

Grids

  1.                 
    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
                    
                
  2. def has_bubble_up(grid, y): for x in range(grid.width): if can_bubble_up(grid, x, y): return True return False
  3. 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 longer_str(str1, str2):
        if len(str1) > len(str2):
            return str1
        return str2
    
    def is_phone_number(str1):
        if not str1.isdigit():
            return False
        if len(str1) != 9 and len(str1) != 10:
            return False
        return True