Quiz 02 Function Writing Practice

Note: Make sure to click the “Show Solutions” button to reveal the solutions before using one of the “Solution” links underneath each function’s description.

Lists

odd_and_even

  • The function name is odd_and_even and has a list[int] parameter.

  • The function should return a list[int].

  • The function should return a new list containing the elements of the input list that are odd and have an even index.

  • The function should not mutate (modify) the input list.

  • Explicitly type variables, parameters, and return types.

  • The following REPL examples demonstrate expected functionality of your value_exists function:

      
    >>> odd_and_even([2,3,4,5]) [] >>> odd_and_even([7, 8, 10, 10, 5, 12, 3, 2, 11, 8]) [7, 5, 3, 11]

Solution

short_words

  • The function name is short_words and has a list[str] as a parameter.

  • The function should return a new list[str] of the words from the input list that are shorter than 5 characters.

  • If a word is not added to the new list because it is too long,the function should print a string stating that it was too long.

  • The function should not mutate(modify) the input list.

  • Explicitly type variables, parameters, andreturn types.

  • Include a Docstring that says: Returns list of words that are shorter than 5 characters.

  • The following REPL examples demonstrate expected functionality of your function:

      
    >>> weather: list[str] = ["sun", "cloud", "sky"] >>> short_words(weather) cloud is too long! ['sun', 'sky']

Solution

multiples

Write a function called multiples. Given a list[int], multiples should return a list[bool] that tells whether each int value is a multiple of the previous value. For the first number in the list, you should wrap around the list and compare this int to the last number in the list.
Example: multiples([2, 3, 4, 8, 16, 2, 4, 2]) should return [True, False, False, True, True, False, True, False].

Solution

Dictionaries

value_exists

  • The function name is value_exists and is called with a dict[str,int] and an int as an argument.

  • The function should return a bool.

  • The function should return True if the int exists as a value in the dictionary, and False otherwise.

  • The function should not mutate (modify) the input dict.

  • Explicitly type variables, parameters, and return types.

  • The following REPL examples demonstrate expected functionality of your value\_exists function:

      
    >>> test_dict: dict[str,int] = {"a": 2, "b": 4, "c": 7, "d": 1} >>> test_val: int = 4 >>> value_exists(test_dict, test_val) True >>> value_exists(test_dict, 5) False

Solution

plus_or_minus_n

  • The function name is plus_or_minus_n and is called with inp: dict[str,int] and n: int as an argument.

  • The function should return None. It instead mutates the input dictionary inp.

  • The function should check if each value in inp is even or odd. If it is even, add n to that value. If it is odd, subtract n.

  • Explicitly type variables, parameters, and return types.

  • The following REPL examples demonstrate expected functionality of your function:

      
    >>> test_dict: dict[str,int] = {"a": 2, "b": 4, "c": 7, "d": 1} >>> test_val: int = 4 >>> plus_or_minus_n(test_dict, test_val) >>> test_dict {"a": 6, "b": 8, "c": 3, "d": -3}

Solution

free_biscuits

Write a function called free_biscuits. Given a dictionary with str keys (representing basketball games) and list[int] values (representing points scored by players), free_biscuits should return a new dictionary of type dict[str, bool] that maps each game to a boolean value for free biscuits. (True if the points add up to 100+, False if otherwise)
Example: free_biscuits({ “UNCvsDuke”: [38, 20, 42] , “UNCvsState”: [9, 51, 16, 23] }) should return { “UNCvsDuke”: True, “UNCvsState”: False }.

Solution

SHOW SOLUTIONS

Note: Your solution does not need to be identical to these, these are just examples of one of many possible solutions!

Lists Solutions

odd_and_even solution

    def odd_and_even(list1: list[int]) -> list[int]:
        """Find the odd elements with even indexes."""
        i: int = 0
        list2: list[int] = []

        while i < len(list1):
            if list1[i] % 2 == 1 and i % 2 == 0:
                list2.append(list1[i])
            i += 1

        return list2

short_words solution

    def short_words(inp_list: list[str]) -> list[str]:
        """Filter out the shorter words"""
        ret_list: list[str] = []
        for x in inp_list:
            if len(x) < 5:
                ret_list.append(x)
            else:
                print(f"{x} is too long!")
        return ret_list

multiples solution

    def multiples(vals: list[int]) -> list[bool]:
        mults: list[bool] = []
        # check first value against last value
        # a is a multiple of b means a % b == 0
        mults.append(vals[0] % vals[len(vals) - 1] == 0)
        # start idx at 1 since we already checked idx 0
        idx: int = 1
        while idx < len(vals):
            # a is a multiple of b means a % b == 0
            mults.append(vals[idx] % vals[idx - 1] == 0)
            idx += 1
        return mults
    def multiples(vals: list[int]) -> list[bool]:
        mults: list[bool] = []
        # check first value against last value
        # a is a multiple of b means a % b == 0
        if vals[0] % vals[len(vals) - 1] == 0:
            mults.append(True)
        else:
            mults.append(False)
        # start idx at 1 since we already checked idx 0
        idx: int = 1
        while idx < len(vals):
            # a is a multiple of b means a % b == 0
            if vals[idx] % vals[idx - 1] == 0:
                mults.append(True)
            else:
                mults.append(False)
            idx += 1
        return mults

Dictionaries Solutions

value_exists solution

    def value_exists(d: dict[str, int], num: int) -> bool:
        for key in d:
            if d[key] == num:
                return True
        return False
    def value_exists(d: dict[str, int], num: int) -> bool:
        exists: bool = False
        for key in d:
            if d[key] == num:
                exists = True
        return exists

plus_or_minus_n solution

    def plus_or_minus_n(inp: dict[str, int], n: int) -> None:
        for key in inp:
            if inp[key] % 2 == 0:
                inp[key] = inp[key] + n
            else: # element is odd
                inp[key] = inp[key] - n
    def plus_or_minus_n(inp: dict[str, int], n: int) -> None:
        for key in inp:
            if inp[key] % 2 == 0:
                inp[key] += n
            else: # element is odd
                inp[key] -= n

free_biscuits solution

    def free_biscuits(input: dict[str, list[int]]) -> dict[str, bool]:
        """Check each game to see if we get free biscuits."""
        result: dict[str, bool] = {}
        # loop over each key in my input dictionary
        for key in input:
            # for each element of the dictionary, sum up its values
            list_to_sum: list[int] = input[key]
            sum: int = 0
            # loop through list and add each value to sum
            for element in list_to_sum:
                sum += element
            # if sum >= 100, store in result under key "key" with value True
            if sum >= 100:
                result[key] = True
            else: # if not, store as False
                result[key] = False
        return result
Contributor(s): Alyssa Lytle, Megan Zhang, David Karash, Coralee Vickers, Carolyn Pierce, Viktorya Hunanyan, Benjamin Eldridge