Skip to the content.
Home Create Task Data Structures Test Prep

Data Structures

Table of Contents

  1. Code
  2. Runtime
  3. Week 0
  4. Week 1
  5. Week 2

Code

Runtime

Week 0

def fibonacci():
    # determine number of terms
    n = int(input("Enter the number of terms in the sequence: "))
    # no negative numbers
    if n < 0:
        raise ValueError
    try:
        i = 0
        # return the fibonacci values to generate sequence
        while i <= n:
            print(fibonacciRecursion(i), end=" ")
            i += 1
        print()
    except ValueError:
        print("Please try again. You must input a positive integer.")

Week 1

def listy(n):
    # using comma puts space between values
    # dicionary name[key] used to find the value that corresponds to the specified key
    print(myList[n]["First Name"], myList[n]["Last Name"])
    # \t is a tab indent, end="" make sure no return occurs
    print("\t", "Sponsors: ", end="")
    # join allows printing a string list with separator (join all sponsors and separate with commas)
    print(", ".join(myList[n]["Sponsors"]))
    print()
# recursion simulates loop incrementing on each call (n + 1) until exit condition is met
def myRecursive(n):
    if n < len(myList):
        listy(n)
        myRecursive(n + 1)
    # exit condition
    return

Week 2

class Factorial:
    def __init__(self):
        pass

    def __call__(self, n):
        # no negative numbers
        if n < 0:
            return "Error! Can't calculate factorial for negative numbers."
        # factorial of 1 and factorial of 0 are both equal to 1
        elif n <= 1:
            return 1
        # calculate the factorial
        else:
            return n * self(n - 1)