Section #3 Solutions

January 31st, 2021


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

String Slicing

  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()

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 ''

                    
                

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:]

def character_counts(s, ch):
    count = 0
    while s.find(ch) != -1:
        count += 1
        index = s.find(ch)
        s = s[:index] + str(count) + s[index + 1:]
    return s

                
            

Word Puzzles

            
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def is_peaceful(word):
    """
    Returns whether a word is peaceful, i.e., whether its letters appear in
    sorted order.

    Arguments:
        word -- The word to check
    >>> is_peaceful('ABORT')
    True
    >>> is_peaceful('FIRST')
    True
    >>> is_peaceful('')
    True
    >>> is_peaceful('PYTHON')
    False
    >>> is_peaceful('CHOCOLATE')
    False
    """

    """
    Python provides a really nice `sorted` function that can sort collections.
    It returns a list, and you can turn a list into a string by joining together
    its elements with a string:
        ''.join(lst)

    We can, therefore, get a nice one-line solution with:
    """
    # return word == ''.join(sorted(word))

    """
    Or, you might prefer the iterative solution, using string comparisons to 
    check if a character is >= the next character (Python lets you compare 
    strings alphabetically!):
    """
    # for i in range(len(word) - 1): # don't check the last letter
    #     if word[i] >= word[i+1]:
    #         return False
    # return True

    """
    And finally, we can use a creative application of the `.find` function to 
    obtain a character's position in the alphabet:
    """
    for i in range(len(word) - 1): # don't check the last letter
        """
        We search for the character in ALPHABET. 
        """
        curr_letter_index = ALPHABET.find(word[i])
        next_letter_index = ALPHABET.find(word[i+1])
        if curr_letter_index >= next_letter_index:
            return False
    return True


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
            
        

File Reading

No More Counting Dollars, We'll Be Counting Words

            
def count_peaceful(filename):
    """
    Return the number of peaceful words in the file
    """
    count = 0
    with open(filename, 'r') as f:
        for line in f:
            word = line.strip().upper()
            if is_peaceful(word):
                count += 1
    return count


def count_stacatto(filename):
    """
    Return the number of stacatto words in the file
    """
    count = 0
    with open(filename, 'r') as f:
        for line in f:
            word = line.strip().upper()
            if is_stacatto(word):
                count += 1
    return count
            
        

Gamestop Trades

            
def parse_substring_from_delims(s, delim):
    # find start and end for substring
    substr_start = s.find(delim) + 1
    substr_end = s.find(delim, substr_start + 1)
    # slice substring from original string s
    substr = s[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_delims(line, "|")
            num_shares = int(parse_substring_from_delims(line, "$"))
            if trade_type == "BUY":
                shares_bought += num_shares
            else:
                shares_sold += num_shares
    print(shares_bought, "shares bought.")
    print(shares_sold, "shares 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)