# Code implemented in CSCI134 on Monday, 9.23.24
# It uses helper functions and flag variables
# to achieve some indexing tasks with strings
# and lists.

# The triple quotes under each function is a docstring-
# tells us what the function will do.
# The interactive python example in the docstring shows
# us what a sample function call with example input
# and output looks like.

def locs_of_char(char, text):
    """ Returns a list of all locations of
    character, char, in str, text.

    >>> locs_of_char('e', "cheese")
    [2, 3, 5]
    """
    # init accumulator
    locs = []

    # look at each ch in string
    for index in range(len(text)):
        # is it a match?
        if text[index] == char:
            # if yes, accumulate
            locs = locs + [index]

    # return accumulator
    return locs

def index_of_char(char, text):
    """
    Returns first location of char in text.

    >>> index_of_char('e', "cheese")
    2
    """
    # look at each ch in text
    for index in range(len(text)):
        # is it a match?
        if text[index] == char:
            # if yes, return location
            return index # leaves the function and destroys function frame
    return -1 # Will this cause a problem in later functions?

def index_of_characters(char, list_of_string):
    """
    Returns first location of char in each string
    from list_of_string...using a HELPER FUNCTION.

    >>> index_of_characters('e', ["eat", "more", "cheese"])
    [0, 3, 2]
    """
    locs = [] # init accumulator

    # look it each word
    for word in list_of_string:
        # look at each character
        # if it's a match, accumulate
        locs = locs + [index_of_char(char, word)]

    return locs # return accumulator

def locs_of_characters(char, list_of_string):
    """
    Returns first location of char in each string
    from list_of_string...using a FLAG VARIABLE.

    >>> locs_of_characters('e', ["eat", "more", "cheese"])
    [0, 3, 2]
    """
    locs = [] # init accumulator

    # look it each word
    for word in list_of_string:
        found = False # have we found the char in this word yet?
        # look at each character
        for index in range(len(word)):
            # if it's a match, accumulate
            if not found and word[index ] == char:
                locs = locs + [index]
                found = True # we've found it!

    return locs # return accumulator


# Code below only executes when our program
# is run as a script.
if __name__ == "__main__":
    # Test locs_of_char
    print(locs_of_char('e', "cheese"))
    print("expected: [2, 3, 5]")
    # Test index_of_char
    print(index_of_char('e', "cheese"))
    print("expected: 2")
    # Test index_of_characters
    print(index_of_characters('e', ["eat", "more", "cheese"]))
    print("expected: [0, 3, 2]")
    # Test locs_of_characters
    print(locs_of_characters('e', ["eat", "more", "cheese"]))
    print("expected: [0, 3, 2]")
