Section #4 Solutions

April 25th, 2021


Written by Juliette Woodrow, Brahm Capoor, Nick Parlante, and John Dalloul

Tracing Problem

                    
b variables:  12 4 16
Main variables:  4 13.0 12
                    
                

String Parsing and Lists

                    

    return email_components

def find_time(str):
    colon_index = str.find(":")
​
    # return empty string if there are no times
    if colon_index == -1:
        return ''
    
    # parse out time
    time = str[colon_index - 2: colon_index + 3]
​
    return time


def parse_out_hashtags(s):
    octothorpe_loc = s.find('#')
    
    #no hashtag, so return empty string
    if octothorpe_loc == -1:
        return ''

    end = octothorpe_loc + 1

    #find the end of the hashtag
    while end < len(s) and s[end].isalnum():
        end += 1

    hashtag = s[octothorpe_loc + 1:end]
  
    return hashtag


def find_price(line, currency):
    """
    We want to look through a line and find the place where a price is mentioned.
    You can assume that the currency symbol specified will only show up once in
    the line provided.
    To find the price, locate the currency symbol and then find all the digits AFTER
    the symbol (not all currencies have the symbol come first--think about how
    we could adjust our code if the symbol came last, instead). Stop reading once the
    last digit has been read. Return the price as an integer (without the currency
    symbol).
    """
    # Find the currency symbol
    symbol_index = line.find(currency)
​
    # Start looking at the first digit (symbol_index + 1) and look for all the digits
    end_of_price = symbol_index + 1
    while end_of_price < len(line) and line[end_of_price].isdigit():
        end_of_price += 1
​
    price = line[symbol_index + 1 : end_of_price]
    return int(price)


def exclaim_words(s):
    exclaim = s.find('!', search)
    
    #if there are no exclamation points, return the empty string 
    if exclaim == -1:
        return ''
    
    # Otherwise, move begin left over alpha chars
    begin = exclaim - 1
    while begin >= 0 and s[begin].isalpha():
        begin -= 1
    
    # In this case, begin is on the first *non* alpha
    word = s[begin + 1:exclaim + 1]
    if len(word) >= 2:  # 1 or more alpha + the !
        return word

    return ''

def parse_username(s):
    at = s.find('@')
    if at == -1:
        return ''
        
    # guard: start >= 0
    start = at - 1
    while start >= 0 and (s[start].isalpha() or s[start].isdigit() or s[start] == '.'):
        start -= 1
    
    # start is on the first *non* alpha
    username = s[start + 1:at]
    return username 

def parse_hostname(s):
    at = s.find('@')
    if at == -1:
        return ''
        
    # guard: end < len(s)
    end = at + 1
    while end < len(s) and (s[end].isalpha() or s[end].isdigit() or s[end] == '.'):
        end += 1
    
    # start is on the first *non* alpha
    hostname = s[at+1:end]
    return hostname 


def parse_phone_number(s):
    start_phone = 0

    #find the start of the phone number
    while start_phone < len(s) and not s[start_phone].isdigit():
        start_phone += 1

    #if end is beyond the end of the string, there are no digits, and we return empty list 
    if start_phone == len(s):
        return []

    #find end of phone number 
    end_phone = start_phone
    while end_phone < len(s) and (s[end_phone].isdigit() or s[end_phone] == '-'):
        end_phone += 1

    phone_num = s[start_phone:end_phone]
    
    first_dash = phone_num.find('-')
    area_code = phone_num[:first_dash]

    second_dash = phone_num.find('-', first_dash + 1)
    rest_of_num = phone_num[first_dash+1:second_dash] + phone_num[second_dash+1:]

    phone_num_lst = []
    phone_num_lst.append(area_code)
    phone_num_lst.append(rest_of_num)
    return phone_num_lst












                    
                

Drawing

                

# given constants
SQUARE_SIDE_LENGTH_RATIO = 0.27
​

def draw_stanford_flag(canvas, left, top, width, height, num_stripes):
    """
    This function draws the outline of the new Stanford flag at the given location
    with the given width and height. The parameters are:
        - canvas: the canvas on which to draw the flag
        - left_x: the x coordinate for the upper left corner of the flag
        - top_y: the y coordinate for the upper left corner of the flag
        - width: the total width of the flag
        - height: the total height of the flag
    """
    stripe_thickness = height // num_stripes #use int division here
    
    # draw the stripes
    start_x = left
    for i in range(num_stripes):
        if i % 2 == 0: #only need to draw red on the even indices of the loop
            # calculate the y coordinate for the upper left corner of the current stripe
            curr_y = top + i * (stripe_thickness)
            canvas.fill_rect(start_x, curr_y, width, stripe_thickness, color = "red")
​
    # draw the green square
    square_side_length = SQUARE_SIDE_LENGTH_RATIO * width 
    square_left = left + width / 2 - square_side_length / 2 # x coord for upper left corner
    square_top = top + height / 2 - square_side_length / 2 # y coord for upper left corner
    canvas.fill_rect(square_left, square_top, square_side_length, square_side_length, color = 'green')

def draw_spider_patch(canvas, left, top, width, height, n):
    canvas.draw_rect(left, top, width, height, color='green')
    for i in range(n):
        x_add = i / (n - 1) * (width - 1)
        # to bottom-right
        canvas.draw_line(left + x_add, top, left + width - 1, top + height - 1)


def draw_flags(canvas, width, height, num_stripes, n):
    """
    This function draws three identical flags on the given canvas, one in the bottom
    left corner, one in the top center, and one in the bottom right corner. The parameters
    are:
        - canvas: the canvas on which to draw the flags
        - width: the total width of the canvas
        - height: the total height of the canvas
    """
    # calculate reference points for patches
    patch_height = height // 2
    patch_width = width // 3
    
    # draw flags
    draw_stanford_flag(canvas, 0, patch_height, patch_width, patch_height, num_stripes)
    draw_stanford_flag(canvas, patch_width, 0, patch_width, patch_height, num_stripes)
    draw_stanford_flag(canvas, patch_width * 2, patch_height, patch_width, patch_height, num_stripes)

    #draw spider patches
    draw_spider_patch(canvas, 0, 0, patch_width, patch_height, n)
    draw_spider_patch(canvas, patch_width, patch_height, patch_width, patch_height, n)
    draw_spider_patch(canvas, patch_width*2, 0, patch_width, patch_height, n)
                
            

Main

            
"""
calculator.py
-------------
Implements the calculator program, as specified in the
section 4 handout.
"""
import sys 

def exp(base, power):
    total = 1
    for i in range(power):
        total *= base
    return total

def square(base):
    return exp(base, 2)

def add(nums):
    total = 0
    for i in range(len(nums)):
        total += int(nums[i])
    return total

def main():
    args = sys.argv[1:]

    operation = args[0]

    if operation == "-exp":
        base = int(args[1]) # convert the argument to an int
        power = int(args[2])
        result = exp(base, power)
        print(result)

    if operation == "-square":
        base = int(args[1])
        result = square(base)
        print(result)

    if operation == "-add":
        nums = args[1:]
        result = add(nums)
        print(results)

if __name__ == "__main__":
    main()