CSC111 / lectures / recursion.py
recursion.py
Raw
def f(n):
    if n == 0:
        return 0
    else:
        return f(n - 1) + n


def sum_nested_v1(nested_list: int | list) -> int:
    """Return the sum of the given nested list.

    This version uses a loop to accumulate the sum of the sublists.
    """
    if isinstance(nested_list, int):
        return nested_list
    else:
        sum_so_far = 0
        for sublist in nested_list:
            sum_so_far += sum_nested_v1(sublist)
        return sum_so_far

def sum_nested_v2(nested_list: int | list) -> int:
    """Return the sum of the given nested list.

    This version uses a comprehension and the built-in sum aggregation function.
    """
    if isinstance(nested_list, int):
        return nested_list
    else:
        return sum(sum_nested_v2(sublist) for sublist in nested_list)

def flatten(nested_list: int | list) -> list[int]:
    """Return a (non-nested) list of the integers in nested_list.

    The integers are returned in the left-to-right order they appear in
    nested_list.
    """
    if isinstance(nested_list, int):
        return [nested_list]
    else:
        result_so_far = []
        for sublist in nested_list:
            result_so_far.extend(flatten(sublist))
        return result_so_far

def nested_list_contains(nested_list: int | list, item: int) -> bool:
    if isinstance(nested_list, int):
        return nested_list == item
    else:
        # v1: return any([nested_list_contains(sub_list, item) for sub_list in nested_list])
        # v2:
        # lst = []
        # for sub in nested_list:
        #     lst.append(nested_list_contains(sub, item))
        # return any(lst)
        # v3:
        bol = False
        for sub in nested_list:
            a = nested_list_contains(sub, item)
            if a == True:
                return True
            bol = a
        return False # WRONG