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

Algorithmic Final Code Segments

OOP Factorial

# Sets class
class factorial:
    def __init__(self):
        self.factorial = []
# Def for self + n
    def __call__(self,n):
        if n == 1 or n == 0:
            self.print()
            return 1
        else:
            self.factorial.append(n)
            return n * self(n-1)
# After calling istelf it prints algorithm result
    def print(self):
        print("="*30, "\nSequence of Numbers: \n", *self.factorial)

def run_factorial():
# First test
    n = 12
    facto = factorial()
    result = facto(n)
    print("="*30, "\nThe factorial of", n, "is", result)

# Second test
    n = 15
    facto = factorial()
    result = facto(n)
    print("="*30, "\nThe factorial of", n, "is", result)

OOP LCM

# no init like the factorial because of no defined properties

class leastcm:
    def __call__(self, a, b):
        if (a > b):
            maximum = a
        else:
            maximum = b
        while (True):
            if (maximum % a == 0 and maximum % b == 0):
                break
            maximum = maximum + 1
        return maximum

def lcm_run():
    #first test
    a = 3
    b = 5
    lcm = leastcm()
    result = lcm(a,b)
    print("="*60, "\nThe LCM of", a, "and", b, "is", result)

    #second test
    a = 50
    b = 100
    result = lcm(a,b)
    print("="*60, "\nThe LCM of", a, "and", b, "is", result)

    #third test
    a = 5
    b = 7
    result = lcm(a,b)
    print("="*60, "\nThe LCM of", a, "and", b, "is", result)

Factorial

def fact(b):
    a = 1
    for i in range(1,b+1):
        a = a * i
    return a
b = 5
number = fact(b)
print("="*30)
print("The Factorial Of 5 Is: ", number)
print("="*30)

Week 1

Python Lists Vs Dictionaries

InfoDB Lists

infoDb = []
# List with dictionary records placed in a list  
infoDb.append({  
               "FirstName": "Siya",  
               "LastName": "Dixit",  
               "DOB": "July 30",  
               "Location": "San Diego",  
               "Personal Email": "dsiya006@gmail.com",  
               "Fav_Colors":["Pink","Blue","Lavender"]  
              })  
x = InfoDb[0]["Fav_Colors"][1] 
result: Blue

There is also a method called get() on the Dictionary(InfoDb[0]) that will give you the same result:

x = InfoDb[0].get("Fav_Colors")[2]
result: Lavender
# given an index this will print InfoDb content
def print_data(n):
    print(InfoDb[n]["FirstName"], InfoDb[n]["LastName"])  # using comma puts space between values
    print("\t", "Colors: ", end="")  # \t is a tab indent, end="" make sure no return occurs
    print(", ".join(InfoDb[n]["Fav_Colors"]))  # join allows printing a string list with separator
    print()



def tester():
    print("For loop")
    for_loop()
    print("While loop")
    while_loop(0)  # requires initial index to start while
    print("Recursive loop")
    recursive_loop(0)  # requires initial index to start recursion

While Loop

# while loop contains an initial n and an index incrementing statement (n += 1)
def while_loop(n):
    while n < len(InfoDb):
        print_data(n)
        n += 1
    return

For Loop

# for loop iterates on length of InfoDb
def for_loop():
    for n in range(len(InfoDb)):
        print_data(n)

Tri 3 TT0 Python Menu, Replit, Github

Python Menu w/ data structures and try/except statements

# menu.py - function style menu
# Imports typically listed at top
# each import enables us to use logic that has been abstracted to other files and folders
import loopy
import mathpy
import funcy
import patterns


# Main list of [Prompts, Actions]
# Two styles are supported to execute abstracted logic
# 1. file names will be run by exec(open("filename.py").read())
# 2. function references will be executed directly file.function()
main_menu = [
    ["Stringy", "stringy.py"],
    ["Listy", "listy.py"],
    ["Loopy", loopy.main],
]

# Submenu list of [Prompt, Action]
# Works similarly to main_menu
sub_menu = [
    ["Factors", mathpy.factors],
    ["GCD", mathpy.gcd],
    ["LCM", mathpy.lcm],
    ["Primes", mathpy.primes],
]

patterns_sub_menu = [
    ["Patterns", "patterns.py"],
    ["PreFuncy", "prefuncy.py"],
    ["Funcy", funcy.ship],
]

# Menu banner is typically defined by menu owner
border = "=" * 25
banner = f"\n{border}\nPlease Select An Option\n{border}"

# def menu
# using main_menu list:
# 1. main menu and submenu reference are created [Prompts, Actions]
# 2. menu_list is sent as parameter to menuy.menu function that has logic for menu control
def menu():
    title = "Function Menu" + banner
    menu_list = main_menu.copy()
    menu_list.append(["Math", submenu])
    menu_list.append(["Patterns", patterns_submenu])
    buildMenu(title, menu_list)

# def submenu
# using sub menu list above:
# sub_menu works similarly to menu()
def submenu():
    title = "Function Submenu" + banner
    buildMenu(title, sub_menu)

def patterns_submenu():
    title = "Function Submenu" + banner
    buildMenu(title, patterns_sub_menu)

def buildMenu(banner, options):
    # header for menu
    print(banner)
    # build a dictionary from options
    prompts = {0: ["Exit", None]}
    for op in options:
        index = len(prompts)
        prompts[index] = op

    # print menu or dictionary
    for key, value in prompts.items():
        print(key, '->', value[0])

    # get user choice
    choice = input("Type your choice> ")

    # validate choice and run
    # execute selection
    # convert to number
    try:
        choice = int(choice)
        if choice == 0:
            # stop
            return
        try:
            # try as function
            action = prompts.get(choice)[1]
            action()
        except TypeError:
            try:  # try as playground style
                exec(open(action).read())
            except FileNotFoundError:
                print(f"File not found!: {action}")
            # end function try
        # end prompts try
    except ValueError:
        # not a number error
        print(f"Not a number: {choice}")
    except UnboundLocalError:
        # traps all other errors
        print(f"Invalid choice: {choice}")
    # end validation try

    buildMenu(banner, options)  # recursion, start menu over again


if __name__ == "__main__":
    menu()