factorial_vs_squared.py

#! /usr/bin/python3
# ===================================================================
# plot a factorial vs squared growth curve
# (compare a function's O(n!) and O(n**2) growth)
# ===================================================================

import math
import user_interface as ui
from graphics import *


# -------------------------------------------------------------------
# ---- plot factorial values
# ---- n = number to factorial
# ---- s = n step for plot
# -------------------------------------------------------------------

def PlotFactorialCurve(win,n,s):

    print(f"plot {n} factorial with a step of {s}")

    for x in range(1,n,s):

        y = math.factorial(x)

        print(f"factiorial {x} is {y}")

        wx = round(x*20)           # scale the X coordinate
        wy = round(win.height - y) # invert Y coordinate

        # ---- stay in the graphics window
        if wx < 0 or wx >= win.width or wy < 0 or wy >= win.height:
            break

        c = Circle(Point(wx,wy),4)
        c.setFill('black')
        c.draw(win)

    return

# -------------------------------------------------------------------
# ---- plot squared values
# ---- n = number to square
# ---- s = n step for plot
# -------------------------------------------------------------------

def PlotSquaredCurve(win,n,s):

    print(f"plot {n} squared with a step of {s}")

    for x in range(1,n,s):

        y = x**2

        print(f"square of {x} is {y}")

        wx = round(x*20)           # scale (spread out) the X coordinate
        wy = round(win.height - y) # invert Y coordinate (go up not down)


        # ---- stay in the graphics window
        if wx < 0 or wx >= win.width or wy < 0 or wy >= win.height:
            break

        c = Circle(Point(wx,wy),4)
        c.setFill('red')
        c.draw(win)

    return

# -------------------------------------------------------------------
# ---- main
# -------------------------------------------------------------------

if __name__ == '__main__':

    n = 200

    win = GraphWin("Factorial vs Squared", 801, 801)
    win.setBackground("white")

    # ---- plot factorial growth

    PlotFactorialCurve(win,n,1)

    # ---- plot n**2

    PlotSquaredCurve(win,n,1)

    ui.pause()

    win.close()