3.14.1 - Libraries

libraries - a collection of certain predefined functions that help simplify code

  • help save time and effort to help simplify code
import math

math.sqrt(64)
8.0

This is an example of importing math into python (imports the function sqrt() to do math)

Hacks

import math

def alg(x,y):
  z = x + y
  a = math.sqrt(z)
  result = math.cos(a)
  print(str(result)) 

alg(1,2)
-0.16055653857469052

In this piece of code I import math, which is a library used in calculation of different things. I then define a function, alg() with the parameters x,y. I add x to y and then make that number equal to z. After that I square root z with the math.sqrt() function from the math library. I set this value to a and then I take the cosine of a with another function, math.cos() which gives me a result. The result is then printed as a string. I later define the parameters x,y as 1,2 in an argument.

3.15.1 - Randomization

randomization - generates a value between two numbers

  • allows for random values to be produced
import random

answer1 = random.randint(0,3)
answer2 = random.randint(1,8)
answer3 = answer1 + answer2
print(answer3)
6

The result will change however this shows two numbers being randomly generated in a certain range of numbers and then adding them.

There are different methods that can be used in randomly generating numbers.

Method Description
seed() Initialize the random number generator
getstate() Returns the current internal state of the random number generator
setstate() Restores the internal state of the random number generator
getrandbits() Returns a number representing the random bits
randrange() Returns a random number between the given range
randint() Returns a random number between the given range
choice() Returns a random element from the given sequence
choices() Returns a list with a random selection from the given sequence
shuffle() Takes a sequence and returns the sequence in a random order
sample() Returns a given sample of a sequence
random() Returns a random float number between 0 and 1
uniform() Returns a random float number between two given parameters
betavariate() Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)
expovariate() Returns a random float number based on the Exponential distribution (used in statistics)
gammavariate() Returns a random float number based on the Gamma distribution (used in statistics)
gauss() Returns a random float number based on the Gaussian distribution (used in probability theories)
lognormvariate() Returns a random float number based on a log-normal distribution (used in probability theories)
normalvariate() Returns a random float number based on the normal distribution (used in probability theories)
vonmisesvariate() Returns a random float number based on the von Mises distribution (used in directional statistics)
paretovariate() Returns a random float number based on the Pareto distribution (used in probability theories)
weibullvariate() Returns a random float number based on the Weibull distribution (used in statistics)

Hacks

import random

list = ["apple", "pear", "strawberry", "banana"]

result = random.choice(list)

print(result)
strawberry

This output will change with the program being run.

import random imports the random library, which allows the use of different functions that are predefined in the library to randomly pick a string or integer from a list. This is useful in shortening code down to a couple of lines.

Some other things that can be imported:

  • import fibo - allows fibonacci sequences to be created with less code
  • import pickle - allows for conversion between bytes and strings/integers
  • import json - allows for conversion between JSON
  • import calendar - allows for calendar integration in python

3.15.2 - Random Generators

random(a,b) - creates a random number between the range a,b and this can include a and b

Coin Flipper:

import random
flip = random.randint(0,1)

if flip == 0:
  print("heads")
else:
  print("tails")
heads

The output can be either heads or tails, depending on the random value that is generated, which is 0 or 1.

50% Chance to get a number:

random(1,100) <= 50

This makes a chance of getting a number that is less than or equal to 50 is 50%.

Hacks

import random

x = random.randint(0,7)

if x >= 5:
  print("green")
elif 3 <= x < 5:
  print("blue")
elif x == 2:
  print("purple")
elif x == 1:
  print("red")
elif x == 0:
  print("orange")
green

This output will change with each run of the program since it is random.

random.randint(12,20) - All numbers within the range of 12 <= x <= 20 are valid outputs of the function. This is because of the parameters defined in the function, which are (12,20). Every other number is excluded from the selection of a random number in this function.

3.16 - Simulation

simulation - imitation of a situation or process to get information on the product

  • Examples: safety, efficiency
  • more effective and and safer to perform as well as less costly
  • might not be as accurate as real life experiments

Four Corners - code vs real life

Real Life

  • less efficient
  • took a lot of time to execute and took a lot of people to perform
  • people have strategies

Simulation

  • more efficient
  • balanced
  • doesn’t allow bias of number chooser
  • strategies can’t be used because it is entirely randomized
import random

status = "in"
while status != "out":
    chooseCorner = input("What corner do you choose?")

    corner = random.randint(1,4)

    if int(chooseCorner) == corner:
        status = "out"
        print("You chose corner number " + chooseCorner + " and you're OUT")
    else:
        print("You chose corner number " + chooseCorner + " and are still in!")
You chose corner number 2 and are still in!
You chose corner number 3 and are still in!
You chose corner number 4 and are still in!
You chose corner number 1 and are still in!
You chose corner number 2 and you're OUT

Code Explanation:

  • random number generator (middle person) = random.randint
  • if player is out = if statements
  • safe/continue playing = else
  • repeat process until there is a winner = while loop

Rolling Dice - simulation

  • allows for a set of numbers to be rolled within seconds


def parse_input(input_string):
    if input_string.strip() in {"1", "2", "3","4", "5", "6"}:
        return int(input_string)
    else:
        print("Please enter a number from 1 to 6.")
        raise SystemExit(1)

import random

def roll_dice(num_dice):
    roll_results = []
    for _ in range(num_dice):
        roll = random.randint(1, 6)
        roll_results.append(roll)
    return roll_results


num_dice_input = input("How many dice do you want to roll? [1-6] ")
num_dice = parse_input(num_dice_input)
roll_results = roll_dice(num_dice)

print("you rolled:", roll_results) 
you rolled: [5, 1, 2]

This output can change depending on the random results.

Game of Life - interactive simulation

Goals:

  • created unpredictable cellular automation
  • evolves without any patterns, entirely random

How it Works:

  • cells are dead/alive (0 or 1)
  • user configures cells and then runs program that randomly generates cells
    • alive = dead cell is surrounded by at least 3 alive cells
    • dead = alive cell is surrounded by 1 or 0 other alive cells
    • survival = alive cell consistently surrounded by 2/3 alive cells stays alive

This program shows the use of iterations, conditionals, and functions being called to create a simulation of some sort.

Hacks

1) One simulation that could be done is finding which path is the longest out of a set of multiple paths. In this case the program would take the measurement of each of the paths and compare it among all the paths and from there decide which path is the shortest.

Extra Credit Code:

x = input("What is the length of path 1?")
print(str(x) + " ft")
y = input("What is the length of path 2?")
print(str(y) + " ft")
z = input("What is the length of path 3?")
print(str(z) + " ft")

path1 = x
path2 = y
path3 = z


pathList = [path1, path2, path3]

fastest = min(pathList)

print("The shortest path is " + str(fastest) + " feet long.")
4679460 ft
245858 ft
4670606 ft
The shortest path is 245858 feet long.

2) Quiz

questions_number = 6
answers_correct = 0
questions = [
    "True or False: Simulations will always have the same result. \n A: True, \n B: False",
    "True or False: A simulation has results that are more accurate than an experiment \n A: True, \n B: False",
    "True or False: A simulation can model real world events that are not practical for experiments \n A: True, \n B: False",
    "Which one of these is FALSE regarding simulations \n A: Reduces Costs, \n B: Is safer than real life experiments, \n C: More Efficient, \n D: More accurate than real life experiments",
    "Which of the following scenarios would be the LEAST beneficial to have as a simulation \n A: A retail company wants to identify the item which sold the most on their website, \n B: A restaurant wants to determine if the use of robots will increase efficiency, \n C: An insurance company wants to study the impact of rain on car accidents, \n D: A sports car company wants to study design changes to their new bike design ",
    "Which of the following is better to do as a simulation than as a calculation \n A: Keeping score at a basketball game, \n B: Keeping track of how many games a person has won, \n C: Determining the average grade for a group of tests, \n D: Studying the impact of carbon emissions on the environment"
]
question_answers = [
    "B",
    "B",
    "A",
    "D",
    "A",
    "D"
]

print("Welcome to the Simulations Quiz!")

def ask_question (question, answer):
    print("\n", question)
    user_answer = input(question)
    print("You said: ", user_answer)

    if user_answer == answer:
        print("Correct!")
        global answers_correct
        answers_correct = answers_correct + 1
    else:
        print("You are incorrect")
    
for num in range(questions_number):
    ask_question(questions[num], question_answers[num])

print("You scored: ", answers_correct, "/6")
Welcome to the Simulations Quiz!

 True or False: Simulations will always have the same result. 
 A: True, 
 B: False
You said:  B
Correct!

 True or False: A simulation has results that are more accurate than an experiment 
 A: True, 
 B: False
You said:  B
Correct!

 True or False: A simulation can model real world events that are not practical for experiments 
 A: True, 
 B: False
You said:  A
Correct!

 Which one of these is FALSE regarding simulations 
 A: Reduces Costs, 
 B: Is safer than real life experiments, 
 C: More Efficient, 
 D: More accurate than real life experiments
You said:  D
Correct!

 Which of the following scenarios would be the LEAST beneficial to have as a simulation 
 A: A retail company wants to identify the item which sold the most on their website, 
 B: A restaurant wants to determine if the use of robots will increase efficiency, 
 C: An insurance company wants to study the impact of rain on car accidents, 
 D: A sports car company wants to study design changes to their new bike design 
You said:  A
Correct!

 Which of the following is better to do as a simulation than as a calculation 
 A: Keeping score at a basketball game, 
 B: Keeping track of how many games a person has won, 
 C: Determining the average grade for a group of tests, 
 D: Studying the impact of carbon emissions on the environment
You said:  D
Correct!
You scored:  6 /6

3) Rolling Dice Simulation - In the rolling dice simulation, the user first picks a number of die that they want to roll, needing to be within a range of 1 to 6. From there the program checks what number is inputted and then rolls the number of die that the user has picked. This is done by choosing a random number between 1 and 6 and then repeating this for the number of die chosen in the beginning. The results of the random numbers generated are then outputted to the user in a list. This is a simulation because it isn’t in real life and it is simpler and faster than in real life. The advantages of this is that it is faster and simpler to do in code than in real life. The disadvantages is that it is less accurate than in real life examples. I think that in this situation a simulation is better in simulation because it is entirely random and gives outputs fast.

4) Changing Dice Simulation:



def parse_input(input_string):
    if input_string.strip() in {"1", "2", "3","4", "5", "6"}:
        return int(input_string)
    else:
        print("Please enter a number from 1 to 6.")
        raise SystemExit(1)

import random

def roll_dice(num_dice):
    roll_results = []
    for _ in range(num_dice):
        roll = random.randint(1, x) # increased range of random number chosen
        roll_results.append(roll)
    return roll_results


num_dice_input = input("How many dice do you want to roll? [1-6] ")
x = int(input("Please enter the number of sides you want the dice to have.")) # variable for sides the dice should have
num_dice = parse_input(num_dice_input)
roll_results = roll_dice(num_dice)

print("you rolled:", roll_results) 
you rolled: [118, 180, 50, 291, 315, 105]

This output will change with each run of code since the conditions can be altered.

3.17 - Undecidable vs Unsolvable Problems

Collatz Conjecture - unsolved math problem that eventually makes a number into 1

  • can’t test every number since they are infinite, so this is unsolved

Example:

Code - Hailstone Numbers:

def collatz(i):
    while i > 1:
        print(i, end=' ')
        if (i % 2):
            # i is odd
            i = 3*i + 1
        else:
            # i is even
            i = i//2
    print(1, end='')
 
 
i = int(input('Enter i: '))
print('Sequence: ', end='')
collatz(i)
Sequence: 6 3 10 5 16 8 4 2 1

This output shows the numbers being processed up until i is 1 an will change with the number inputted.

Hacks

list = [i]
iterations = 0

def collatz(i):
    global list
    global iterations
    while i != 1:
        if (i % 2):
             i =int(3*i + 1)
             list.append(i)
             iterations += 1
        else:
            i = int(i/2)
            list.append(i)
            iterations += 1
    else:
      print("Number of iterations: " + str(iterations))
      print("Sequence: " + str(list))

i = int(input("Enter a number:"))
print("Inputted number: " + str(i))
collatz(i)
Inputted number: 34
Number of iterations: 13
Sequence: [34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]

3.18 - Algorithmic Efficiency

Inefficient Algorithm - Sorting

# This creates a function called inefficientWay with a parameter called number.
def inefficientWay(numbers):
 # Then it loops over the numbers
 for i in range(len(numbers)):
   # Now it finds the minimum number in the unsorted part of the list
   min_index = i
   for j in range(i+1, len(numbers)):
     if numbers[j] < numbers[min_index]:
       min_index = j
   # Then it swaps the minimum number with the first unsorted number
   numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
 # return the sorted list
 return numbers
 
# test the algorithm
print(inefficientWay([2, 4, 5, 1, 3]))  # should print [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

Efficient Algorithm - Sorting (with loop)

def efficient_sort(numbers):
 # loop over the numbers
 for i in range(len(numbers)):
   # find the minimum number in the unsorted part of the list
   min_index = i
   for j in range(i+1, len(numbers)):
     if numbers[j] < numbers[min_index]:
       min_index = j
   # swap the minimum number with the first unsorted number
   numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
 # return the sorted list
 return numbers
 
# test the algorithm
print(efficient_sort([2, 4, 5, 1, 3]))  # should print [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

Hacks

Efficient:

list = []
count = 0

while count < 4:
  i = input("Type something!")
  list.append(i)
  count += 1

if count == 4:
  print("Here is what you typed: ")
  for x in list:
      print("- " + str(x))
  print("Finished!")
Here is what you typed: 
- a
- b
- c
- d
Finished!
  • This box of code uses a loop to cycle through the decision of asking the user to input their string. This string is then put into a list which is later cycled through with another loop after a certain number of inputs have been achieved. The loop goes through the created list and outputs the user’s inputs into a formatted list. This is much more efficient because there isn’t one line of code that is repeated in the program, meaning that the programs cycles on it’s own to repeat a certain action.


Inefficient:

count = 0

print("Here is what you typed: ")

a = input("Type something!")
print("- " + str(a))
count += 1
b = input("Type something!")
print("- " + str(b))
count += 1
c = input("Type something!")
print("- " + str(c))
count += 1
d = input("Type something!")
print("- " + str(d))
count += 1

if count == 4:
  print("Finished!")
Here is what you typed: 
- a
- b
- c
- d
Finished!
  • This box of code repeats the same line of code multiple times in order to ask for an input from the user, to print out the user input, and then to add a number to a counter. When this counter reaches a certain number it states that the program is finished. This is much less efficient because the same code is repeated multiple times, when a loop can be used to repeat it.