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! Screenshot 2022-12-11 221853

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: Open New Terminal In VSCode: pip3 install --upgrade pip pip install numpy

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

Example of using NumPy for arrays:

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, 1])
print("Polynomial function, f(x):", 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 x + 1
Derivative, f(x)'=  
2
When x=5  f(x)'= 2

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

CollegeBoard

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):
    sum = 0
    while n != 0:
        sum = sum + random.randint(1, 6)
        n = n - 1
    return sum
    
Dice(5) # Will output a range of 5 to 30
17

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.

# 1

import random

# Generate a list of n random numbers
n = int(input("How many numbers would you like to generate?"))
a = int(input("What is the minimum number you would like to generate?"))
b = int(input("What is the maximum number you would like to generate?"))
numbers = [random.randint(a, b) for _ in range(n)]

# Sort the numbers into even and odd lists
evens = []
odds = []
for number in numbers:
    if number % 2 == 0:
        evens.append(number)
    else:
        odds.append(number)

# Print the even and odd lists
print(evens)
print(odds)
            
[28, 36, 4, -2, 18, 30, 22, -14, 20, 8, 2, -12]
[-11, 5, 37, 33, 1, 9, -13, 9]
# 2a

import numpy as np

# Define the polynomial as a NumPy array
poly = np.poly1d([2, 0, 0, -6, 24, 0])

# Compute the derivative of the polynomial
derivative = poly.deriv()

# Print the result
print("The derivative of \n" + str(poly) + "\n" + str(derivative))
The derivative of 
   5     2
2 x - 6 x + 24 x
    4
10 x - 12 x + 24
# 2b

import numpy as np

# Define the polynomial using the poly1d class (numerator)
n = np.poly1d([13, 0, 4, 0, 0])

# Define the polynomial using the poly1d class (denominator)
d = np.poly1d([2])

# Compute the derivative of the polynomial using the deriv function and quotient rule
derivative = ((d * n.deriv()) - (d.deriv() * n)) / 4

# Evaluate the derivative at x = 9
result = derivative(9)


print("The derivative of \n" + str(n) + "\n ------" + str(d) + "\nis: \n" + str(derivative))
print("\nWhen x = 9, the derivative is \n" + str(round(result)))
The derivative of 
    4     2
13 x + 4 x
 ------ 
2
is: 
    3
26 x + 4 x

When x = 9, the derivative is 
18990
# 3

# Import the random module
import random

# Create a list of dogs and cats
dogs = ['Dog 1', 'Dog 2', 'Dog 3', 'Dog 4', 'Dog 5', 'Dog 6', 'Dog 7', 'Dog 8', 'Dog 9', 'Dog 10']
cats = ['Cat 1', 'Cat 2', 'Cat 3', 'Cat 4', 'Cat 5', 'Cat 6', 'Cat 7', 'Cat 8', 'Cat 9', 'Cat 10']

# Create a list of tuples, where each tuple contains an animal and a random number
animals = []
for dog in dogs:
    animals.append((dog, random.randint(1, 20)))
for cat in cats:
    animals.append((cat, random.randint(1, 20)))

# Sort the list of tuples based on the random numbers
animals.sort(key=lambda x: x[1])

# Print the animals in the randomized order
for animal in animals:
    print(animal[0])
Cat 3
Dog 1
Dog 4
Dog 7
Dog 6
Dog 10
Dog 2
Cat 7
Cat 8
Dog 5
Cat 5
Cat 10
Cat 6
Cat 4
Cat 9
Dog 3
Cat 1
Dog 9
Dog 8
Cat 2

Python Libraries Hacks

PyGame

  • Free and open-source library for making multimedia applications in Python

  • Provides a set of Python modules for writing games, animations, and other graphical programs

  • Built on top of the popular SDL (Simple DirectMedia Layer) library

  • Important for coders because it allows them to easily create graphical programs using Python

  • Useful for people who want to make games, animations, or other types of interactive programs that involve graphics and multimedia

  • It's free with no license required

Web2py

  • Full-stack web development framework for Python

  • Provides a wide range of features and tools for building and deploying web applications, including a web-based IDE, an object-relational mapper, and a web-based administrative interface

  • Useful because it makes it easy to build and deploy web applications quickly

  • Web-based IDE allows developers to edit, debug, and manage their applications from any web browser, and the object-relational mapper automatically generates the necessary SQL code for working with a database

  • Administrative interface allows developers to easily manage user accounts, access logs, and other administrative tasks

  • Great security features

    • Includes built-in support for encryption and authentication, and it is designed to prevent common web vulnerabilities such as cross-site scripting and SQL injection attacks

    • Open-source and free to use, making it a good choice for developers who want a powerful, easy-to-use web development framework without having to pay for a license