wget https://raw.githubusercontent.com/aidenhuynh/CS_Swag/master/_notebooks/2022-11-30-randomvalues.ipynb

Libraries

  • A library is a collection of precompiled codes that can be used later on in a program for some specific well-defined operations.
  • These precompiled codes can be referred to as modules. Each module contains bundles of code that can be used repeatedly in different programs.
  • A library may also contain documentation, configuration data, message templates, classes, and values, etc.

Why are libraries important?

  • Using Libraries makes Python Programming simpler and convenient for the programmer.
  • One example would be through looping and iteration, as we don’t need to write the same code again and again for different programs.
  • Python libraries play a very vital role in fields of Machine Learning, Data Science, Data Visualization, etc.

A few libraries that simplify coding processes:

  • Pillow allows you to work with images.
  • Tensor Flow helps with data automation and monitors performance.
  • Matplotlib allows you to make 2D graphs and plots.

The AP Exam Refrence Sheet itself is a library!

Hacks:

Research two other Python Libraries NOT DISCUSSED DURING LESSON and make a markdown post, explaining their function and how it helps programmers code.

API’s

  • An Application Program Interface, or API, contains specific direction for how the procedures in a library behave and can be used.
  • An API acts as a gateway for the imported procedures from a library to interact with the rest of your code.

Activity: Walkthrough with NumPy

  • Install NumPy on VSCode:
    1. Open New Terminal In VSCode:
    2. pip3 install --upgrade pip
    3. pip install numpy

REMEMBER: When running library code cells use Python Interpreter Conda (Version 3.9.12)

Example of using NumPy for arrays:

2 more libraries:

Random: gives a random value for a selected data type

numpy: lets you use very cool mathematical functions

import numpy as np
new_matrix = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
 
print (new_matrix)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Example of using NumPy for derivatives:

import numpy as np
 
# defining polynomial function
var = np.poly1d([2, 0, 1])
print("Polynomial function, f(x):\n", var)
 
# calculating the derivative
derivative = var.deriv()
print("Derivative, f(x)'=", derivative)
 
# calculates the derivative of after
# given value of x
print("When x=5  f(x)'=", derivative(5))
Polynomial function, f(x):    2
2 x + 1
Derivative, f(x)'=  
4 x
When x=5  f(x)'= 20

Random Values

  • Random number generation (RNG) produces a random number (crazy right?)
    • This means that a procedure with RNG can return different values even if the parameters (inputs) do not change
  • CollegeBoard uses RANDOM(A, B), to return an integer between integers A and B.
    • RANDOM(1, 10) can output 1, 2, 3, 4, 5, 6, 7, 8, 9, or 10
    • In Python, this would be random.randint(A, B), after importing Python's "random" library (import random)
    • JavaScript's works a little differently, with Math.random() returning a value between 0 and 1.
      • To match Python and CollegeBoard, you could make a procedure like this

CollegeBoard Example: What is the possible range of values for answ3

Convert the following procedure to Python, then determine the range of outputs if n = 5.


PROCEDURE Dice(n)
    sum ← 0
    REPEAT UNTIL n = 0
        sum ← sum + RANDOM(1, 6)
        n ← n - 1
    RETURN sum

import random # Fill in the blank

def Dice(n):
    sun = 0
    while (n >= 0):
        sun = sun + random.randint(1, 6)
        n -= 1
    return sun
Dice(5) # Will output a range of 5 to 30
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/dashpen/vscode/blog/_notebooks/2022-11-30-randomvalues.ipynb Cell 10 in <cell line: 10>()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/dashpen/vscode/blog/_notebooks/2022-11-30-randomvalues.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a>     return sun
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/dashpen/vscode/blog/_notebooks/2022-11-30-randomvalues.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a> Dice(5) # Will output a range of 5 to 30
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/dashpen/vscode/blog/_notebooks/2022-11-30-randomvalues.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a> p = numpy.poly1d()

TypeError: __init__() missing 1 required positional argument: 'c_or_r'

Homework

  1. Write a procedure that generates n random numbers, then sorts those numbers into lists of even and odd numbers (JS or Python, Python will be easier).

  2. Using NumPy and only coding in python cell, find the answer to the following questions: a. What is the derivative of 2x^5 - 6x^2 + 24x? b. What is the derivative of (13x^4 + 4x^2) / 2 when x = 9?

  3. Suppose you have a group of 10 dogs and 10 cats, and you want to create a random order for them. Show how random number generation could be used to create this random order.

import numpy
import random

def listMaker(n):
    list = []
    for each in range(n):
        list.append(random.randint(1, 100))
    list.sort()
    return list
print(listMaker(10))
p = numpy.poly1d([2, 0, 0, -6, 24, 0])
p2 = numpy.poly1d([13/2, 0, 2, 0, 0])

pder = p.deriv()
print(pder)

p2der = p2.deriv()
print(p2der)

print(p2der(9))

cats = {
    "1" : "amy",
    "2" : "aljazerra",
    "3" : "alamo",
    "4" : "azerbaijan",
    "5" : "allo",
    "6" : "attack",
    "7" : "anarchy",
    "8" : "as",
    "9" : "away",
    "10" : "a"
}

dogs = {
    "1" : "bob",
    "2" : "billy",
    "3" : "bleh",
    "4" : "bojangles",
    "5" : "bruh",
    "6" : "barrack obama",
    "7" : "bill clinton",
    "8" : "black",
    "9" : "bjorn",
    "10" : "bangladesh"
}

def randIntArray(n):
    array = []
    while (len(array) <= n - 1):
        num = random.randint(1, n)
        bad = False
        for each in array:
            if (num == each):
                bad = True
        if (bad == False):
            array.append(num)

    return array

def randBoolArray(n):
    array = randIntArray(n)
    newArray = []
    for each in array:
        if(each > n/2):
            newArray.append(True)
        else:
            newArray.append(False)
    return newArray


def randomOrder():
    indexCat = randIntArray(10)
    indexDog = randIntArray(10)
    index = randBoolArray(20)
    for each in range(20):
        if(index[each]):
            print(cats[str(indexCat[0])] + " in position " + str(each + 1))
            indexCat.pop(0)
        else:
            print(dogs[str(indexDog[0])] + " in position " + str(each + 1))
            indexDog.pop(0)

randomOrder()
# all of the names are unique and only 10 dogs and 10 cats are present
        
[16, 21, 25, 40, 44, 50, 51, 78, 89, 96]
    4
10 x - 12 x + 24
    3
26 x + 4 x
18990.0
bojangles in position 1
amy in position 2
azerbaijan in position 3
bangladesh in position 4
barrack obama in position 5
bleh in position 6
alamo in position 7
bob in position 8
allo in position 9
attack in position 10
bill clinton in position 11
as in position 12
aljazerra in position 13
bjorn in position 14
away in position 15
a in position 16
anarchy in position 17
black in position 18
bruh in position 19
billy in position 20