Section #3 Solutions

October 10th, 2021


Written by Juliette Woodrow, Anna Mistele, John Dalloul, and Parth Sarin

String Slicing

Part 1

  1. s[1:6]
  2. s[:2] or s[0:2]
  3. s[6:9]
  4. s[6:] or s[6:10]
  5. s[6] or s[6:7]
  6. s[:] or s[0:10] (or just s)
  7. s.upper()
  8. s.lower()
  9. s[-1]
  10. s[-3:]

Part 2

                        
>>> s = 'yyy #xyz &ttt {CS106A} ^goodTimes !'
>>>
>>> hash_loc = s.find('#')
>>> s[hash_loc: hash_loc + 4] 
>>>
>>> amper = s.find('&')
>>> s[amper + 1 : amper + 4]
>>>
>>> open_brace = s.find('{')
>>> close_brace = s.find('}')
>>> s[open_brace + 1: close_brace]
>>>
>>> s[open_brace + 1: close_brace].lower()
>>>
>>> hat = s.find('^')
>>> s[hat:].lower()
>>>
>>> s[hash_loc + 1: close_brace + 1] # or s[hash_loc + 1: hat - 1]
>>>
>>> s[:hash_loc-1] # or s[:3]


                        
                    

String Searching

                    
def defront(s):
    if len(s) >= 2:
        return s[2:]
    return s


def x_end(s):
    found = s.find('x')
    if found != -1:
        return s[found:]
    return ''


def is_valid_password(password):
    exclamation_index = password.find("!")
    # check for presence of !
    if exclamation_index == -1:
        return False
    and_index = password.find("&")
    # check for presence of &
    if and_index == -1:
        return False
    # check for ordering of ! and &
    if and_index < exclamation_index:
        return False
    # check for number of characters
    if exclamation_index <= (len(password) - and_index - 1):
        return False
    # if checks don't return false, password checks out
    return True


def at_word(s):
    at1 = s.find('@')
    if at1 != -1:
        at2 = s.find('@', at1 + 1)
        if at2 != -1:
            return s[at1 + 1:at2]
    return ''


def bracket_money(s):
    open_brace = s.find('{')
    if open_brace == -1:
        return ''

    close_brace = s.find('}', open_brace+1)
    if close_brace == -1:
        return ''

    str_money = s[open_brace + 1: close_brace]
    return int(str_money)

                    
                

String Construction

                
def make_gerund(s):
    """This function adds 'ing' to the end of the given string s and returns this new word. If the given world already 
    ends in 'ing' the function adds an 'ly' to the end of s instead before returning.
    >>> make_gerund('ringing')
    'ringly'
    >>> make_gerund('run')
    'runing'
    >>> make_gerund('')
    'ing'
    >>> make_gerund('ing')
    'ly'
    """
    #if it already ends in ing, add an 'ly' instead 
    if len(s) >= 3 and s[len(s)-3:] == 'ing':
        s = s[0:len(s)-3] + 'ly'
    else:
        s = s + 'ing'

    return s


def put_in_middle(outer, inner):
    """This function inserts the string inner into the middle of the string outer and returns this new value
    >>> put_in_middle('Absolutely', 'freaking')
    'Absolfreakingutely'

    >>> put_in_middle('ss', 'mile')
    'smiles'

    >>> put_in_middle('hit', 'obb')
    'hobbit'
        """

    middle = len(outer) // 2
    return outer[0:middle] + inner + outer[middle:]



                
            

Word Puzzle

            
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'




def is_stacatto(word):
    """
    Returns whether a word is a stacatto word, i.e., whether the letters in
    even positions are vowels.

    Arguments:
        word -- The word to check

    >>> is_stacatto('AUTOMATIC')
    True
    >>> is_stacatto('POPULATE')
    True
    >>> is_stacatto('')
    True
    >>> is_stacatto('PYTHON')
    False
    >>> is_stacatto('SPAGHETTI')
    False
    """
    VOWELS = 'AEIOUY'
    for i in range(len(word)):
        if i % 2 == 1:
            even_letter = word[i]
            if not even_letter in VOWELS:
                return False # we've found an even letter that isn't a vowel,
                             # so we can return immediately.

    return True
            
        

Gamestop Trades

            
def parse_substring_from_strs(line, start_str, end_str):
    # find start and end for substring
    substr_start = line.find(start_str) + len(start_str)
    substr_end = line.find(end_str, substr_start)
    # slice substring from original string s
    substr = line[substr_start:substr_end]
    return substr
‚Äč

def parse_trades(filename):
    shares_bought, shares_sold = 0, 0
    with open(filename, 'r') as f:
        for line in f:
            line = line.strip()
            trade_type = parse_substring_from_strs(line, "||", "|")
            num_shares = int(parse_substring_from_strs(line, "$$", "$"))
            if trade_type == "BUY":
                shares_bought += num_shares
            else:
                shares_sold += num_shares
    print(shares_bought, "shares bought.")
    print(shares_sold, "shares sold.")


def find_percent_seller(filename, entity_name):
    entity_sold, total_sold = 0, 0
    with open(filename, 'r') as f:
        for line in f:
            line = line.strip()
            trade_type = parse_substring_from_strs(line, "||", "|")
            if trade_type == "SELL":
                num_sold = int(parse_substring_from_strs(line, "$$", "$"))
                curr_name = parse_substring_from_strs(line, "&&", "&")
                if curr_name == entity_name:
                    entity_sold += num_sold
                total_sold += num_sold
    entity_percent = entity_sold / total_sold * 100
    print(entity_name, "sold", entity_percent, "percent of GME stock sold.")

            
        

Pylib

            
def create_pylib(filename):
    for line in open(filename):
        line = line.strip()
        open_bracket = line.find("[")
        close_bracket = line.find("]")
        category = line[open_bracket + 1 : close_bracket]
        replacement_word = get_word(category)
        finished_line = line[:open_bracket] + replacement_word + line[close_bracket + 1:]
        print(finished_line)