Unit 3 Sections 1-2

Notes

  • Variable is an abstraction inside a program that can hold a value
  • organizes data by labeling it with descriptive name
  • consists of three parts: name, value, and type
  • When naming variables, keep it easy and simple to read, because it can be messy and confusing later on
  • types of data, integer is a number, text/string is a word, and Boolean is data that determines if something is true or false
  • assignment operator allows a program to change the value represented by a variable, used to assign values to variables
  • value stored in a variable will be the most recent value assigned

Data Abstraction

  • Method used in coding to represent data in a useful form, by taking away aspects of data that aren't being used in the situation
  • Variables and lists are primary tools in data abstraction
  • Provides a separation between the abstract properties of a data type and the concrete details of its representation

Lists & Strings

  • List = ordered sequence of elements
  • Element = individual value in a list that is assigned to a unique index
  • Index = a way to reference the elements in a list or string using natural numbers; each element of a string is referenced by an index
  • String = ordered sequence of characters (Letters, numbers, special characters)

What are Lists?

  • Allow for data abstraction
  • Bundle variables together
  • Store multiple elements
  • Allows multiple related items to be treated as a single value
  • Give one name to a set of memory cells
  • Can keep adding elements to it as needed
  • Can store elements as a single variable by using a list

3 Types of List Operations

  1. Assigning values to a list at certain indices
  2. Creating an empty list and assigning it to a variable
  3. Assigning a copy of one list to another list (setting one list equal to another list)

Practice

colorList=["green", "red", "pink", "purple", "blue", "brown"]

print(str(colorList))
['green', 'red', 'pink', 'purple', 'blue', 'brown']

Homework

print("General Knowledge Trivia")
QandA = { 
    "#1) What is the largest mammal?": "blue whale", 
    "#2) What is the largest organ in the body?": "skin", 
    "#3) What galaxy do we live in?": "milky way", 
    "#4) Who founded Amazon?": "jeff bezos", 
    "#5) What is the world's largest ocean?": "pacific ocean", 
}

def qandresp(question): # display question, return inputted response
    print(question)
    resp = input()
    return resp

correct = 0 

# Setup
print("Current number of questions: " + str(len(QandA)))

# iterate over each key
for key in QandA:
    rsp = qandresp(key) # save user's response to a variable rsp
    rsp = rsp.lower() # answer is case sensitive, so match response to lowercase for answer key to work
    if rsp == QandA[key]: # check if the response is equal to the answer in the dictionary
        print(f"Correct!")
        correct += 1
    else:
        print(f"{rsp} is incorrect ") 

percent = str(round(correct/len(QandA), 2)*100) # calculate percentage

print("You scored " + str(correct) +"/" + str(len(QandA)))
print(f"Which is also, {percent}%") # print score and percentage
General Knowledge Trivia
Current number of questions: 5
#1) What is the largest mammal?
Correct!
#2) What is the largest organ in the body?
heart is incorrect 
#3) What galaxy do we live in?
Correct!
#4) Who founded Amazon?
Correct!
#5) What is the world's largest ocean?
atlantic ocean is incorrect 
You scored 3/5
Which is also, 60.0%

Unit 3 Sections 3-4

Notes

  • An algorithm has three components: sequencing, selection, and iteration
  • sequencing is algorithms doing tasks in the order of specification
  • selection is allowing is to choose two different outcomes based off a decision
  • iteration is that if a condition is true, then the code is repeated

Algorithm Can Be Represented In Two Ways

  • flowcharts, which uses shapes and arrows to represent steps of an algorithm
  • pseudocode, which is a blend of human language and coding format

Basic Operations

  • subtraction, represented by -
  • addition, represented by +
  • multiplication, represented by *
  • division, represented by /
  • getting the remainder, represented by MOD(% in python)

Different Ways Values Are Stored in Variables

  • numerical value stored in variable
  • value of another variable stored in variable
  • result of an operation stored in a variable
  • result of a procedure call stored in a variable

Strings

What is a String? A String: A string is a collection of characters. What is a character as character can be anything from numbers, letters, spaces, special symbols, etc.

A string is a collection of characters. What is a character as character can be anything from numbers, letters, spaces, special symbols, etc.

Certain procedures may be used with strings and they vary from programming language to language Python examples

len() to find the length of a string

lower() to convert to lowercase

etc. Pseudocode examples

len() returns the length of a string

concat() returns a string made up of the concatenated strings ex. concat("string1", "string2") would return string1string2

substring() returns the characters from the string beginning at the at the first position to the last so an example of this would be substring ("abcdefghijk", 2, 5) would print bcde (pseudocode starts at 1)

Homework

Tracking Variables Hack

Num1 = 50
Num2 = Num1 % 9 + 15
Num3 = Num2 / Num1 + ( Num2 * 2 )
Num4 = Num3 + Num1 / 5 - 10
Result = Num4 - Num2
# Result is 20.4
Num1 = 10
Num2 = Num1 % 3 * 4
Num1 = Num2
Num3 = Num1 * 3
Result = Num3 % 2
# Result is 0
valueA = 4
valueB = 90
valueC = 17
valueB = valueC - valueA
valueA = valueA * 10
if valueB > 10:
    print(valueC)
# Result is 17 
17
type = "curly"
color = "brown"
length = "short"
type = "straight"
hair = type + color + length
print(hair)
# Result is straightbrownshort
straightbrownshort

String Hacks

Problem 1
Noun = "Mr.Mortenson"
Adjective = "handsome"
Adjective2 = "Very"
Verb = "is"
abrev = Noun[:7]
yoda = abrev + " " + Verb + " " + Adjective2 + " " + Adjective + "."
print(yoda)
Mr.Mort is Very handsome.
Problem 2
cookie = "choclate"
cookie2 = "rasin"
len1 = len(cookie) / 2
len2 = len(cookie2) * 45
vote1 = (str(cookie) + " vote " + str(len2))
vote2 = (str(cookie2) + " vote " + str(len1))
votes = (str(vote1) + " " + str(vote2))
print(votes)
choclate vote 225 rasin vote 4.0

Unit 3 Sections 8-10

Notes

Lists: a sequence of variables

  • we can use lists to store multiple items into one variable
  • used to store collections of data
  • changeable, ordered, allow duplicates

There is list, then four total collection data types in Python

  • Tuple: collection that is ordered, unchangeable, allows duplicates
  • Set: collection that is unordered, unchangeable, doesn't allow duplicates
  • Dictionary: collection that is ordered, changeable, doesn't allow duplicates

More Terms

  • Index: a term used to sort data in order to reference to an element in a list (allows for duplicates)
  • Elements: the values in the list assigned to an index

Methods

Method Definition Example
append() adds element to the end of the list fruits.append("watermelon")
index() returns the index of the first element with the specified value fruits.index("apple")
insert() adds element at given position fruits.insert(1, "watermelon")
remove() removes the first item with the specified value fruits.remove("strawberry")
reverse() reverses the list order fruits.reverse()
sort() sorts the list fruits.sort()
count() returns the amount of elements with the specified value fruits.count("apple")
copy() returns a copy of the list fruits.copy()
clear() removes the elements from the list fruits.clear()

Iteration

  • Iteration is the repetition of a process or utterance applied to the result or taken from a previous statement.
  • There's a lot of types of iteration though, what to use? How do we apply iteration to lists?
  • Some methods include using a "for loop", using a "for loop and range()", using a "while loop", and using comprehension
  • here are 2 types of iteration: definite and indefinite. Definite iteration clarifies how many times the loop is going to run, while indefinite specifies a condition that must be met

Else, elif, break

  • Else: when the condition does not meet, do statement()
  • Elif: when the condition does not meet, but meets another condition, do statement()
  • Break: stop the loop

Homework

HW Iteration

words = ["alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliett", "kilo",
"lima", "mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey", "xray", "yankee", "zulu"]

inp = input().lower()
print(inp + " ->")
for i in range(len(inp)):
    for j in range(len(words)):
        if inp[i] == words [j][0]:
            print(words[j])
derek ->
delta
echo
romeo
echo
kilo

Other way to print matrix

keypad =   [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9],
            [" ", 0, " "]]
def print_matrix3(matrix):
    for i in range(len(keypad)):
        print(*keypad[i])
print_matrix3(keypad)
1 2 3
4 5 6
7 8 9
  0  

Birth Month HW

keyboard = [["`", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "-", "="],
            ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]"],
            ["A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'"],
            ["Z", "X", "C", "V", "B", "N", "M", ",", ".", "/"]]

      
print(str(keyboard[0][1]) + str(keyboard[3][9]) + str(keyboard[0][1]) + str(keyboard[0][7]) + str(keyboard[3][9]) + str(keyboard[0][2]) + str(keyboard[0][10]) + str(keyboard[0][10]) + str(keyboard[0][5]) + "\n" + str(keyboard[0][1]) + str(keyboard[0][7]))
1/17/2005
17

Unit 3 Sections 9-11

Notes

Algorithms

  • Algorithms can be written in different ways and still accomplish the same tasks
  • Algorithms that appear similar can yield different side effects or results.
  • Some conditional statements can be written as the same as Boolean expressions (VICE VERSA)
  • Different algorithms can be developed or use to solve the same problem.

Conditionals vs. Boolean

The condition and instructions are what differ, that's where the magic happens. The condition is a boolean expression when an expression outputs either true or false. Boolean values are another type of data type in programming languages, and they can only ever hold true or false.

Selection vs. Iteration

Selection:

  • A process used in algorithms where a conditional if-statement leads to one of two outcomes
  • Outcome 1: if the conditional statement is true, something will happen
  • Outcome 2: if the conditional statement is false, something else will happen

Iteration

  • A process used in algorithms that allows certain things to happen until a condition is satisfied
  • Once the condition is satisfied, then an outcome is produced
  • This can take the form of a for-loop, while-loop, and/or if-statement

Takeaways

  • You can use code you've previously wrote in order to make a project easier.
  • Breaking algorithms down into steps can make things easier and more simple.

Homework

Flowchart

Link to flowchart

import random

def RandomNumGen(x):
    RandomNumGenList = []
    
    while x > 0:
        RandomNumGenList.append(random.randint(1,20))
        x -= 1

    print(RandomNumGenList)
    return max(RandomNumGenList)

RandomNumGen(3)
[1, 16, 18]
18

Unit 3 Sections 12-13

Notes

Calling Procedures

Slide 1:

  • A procedure is a named group of programming instructions that may have parameters and return values.
  • Procedures are referred to by different names, such as method or function, depending on the programing language.
  • Parameters are input values of a procedure. Arguments specify the values of the parameters when procedure is called.
  • A procedure call interrupts the sequential execution of statements causing the program to execute the statements within the procedure before continuing. One the last statement in the procedure (or a return statement) has executed, flow or control is returned to the point immediately following where the procedure was called.

Slide 2:

  • When calling procedures, it's important to take notice to whether it returns data, or a block of statements.
  • If the procedure just returns a block of statements, you call the procedure by referring to the procedure name, and inputting the arguments.
  • If the procedure returns some sort of data like a boolean or value, then you will assign that value to a variable

Slide 3:

  • Assume the Temperature outside is Fahrenheit.
  • The procedure convertFahrenheit is intended to convert from Fahrenheit to Celsius.
  • Convert the following psuedocode to python

Developing Procedures

Slide 8:

Picking a descriptive name is important in case you revisit the code later on (separate words with capitals) There are 2 different types of procedures- ones that return a value and those that simply execute a block of statements Steps of developing procedure: picking a useful name, thinking of parameters (what data does the procedure need to know), making a flowchart or writing procedure in pseudocode, and actually developing the procedure.

Slide 9:

In this example, a teacher is writing a program that will replace the grade on a previous quiz if the new grade is better than the previous.

  • What would be a good name for this procedure?
  • What parameters do we need for this procedure?
  • Try writing this procedure out in python based on the given pseudocode

Procedural Abstraction

  • One type of abstraction is procedural abstraction which provides a name for a process and allows a procedure to be used only knowing what it does and not how it does it
  • This is very helpful in managing complexity in a program
  • Subdivision of a program into separate subprograms is called modularity
  • A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for program reuse, which helps manage complexity
  • When a pre-written procedure is called, you don’t necessarily need to know the details of this, just what it does and how to call it
  • Simply, procedural abstraction is naming and calling a pre-written procedure
  • Making sure to include the right arguments so the procedure can do what its supposed to do is crucial
quizGrade = 25
def currentGrade(currentPoints):    
    currentGrade = currentPoints / 40
    currentGrade = currentGrade * 100
    return currentGrade

newPoints = int(input("What did you get out of 40?"))
newPercent = (currentGrade(int(newPoints)))

if (newPoints > quizGrade):
    newquizGrade = newPercent
    print("your new grade is " + str(newquizGrade) + "%")
else:
    print("your grade is still " + str(quizGrade) + "/40")
    
your new grade is 87.5%

Homework

class Student:
    marks = []
    def getData(self, rn, name, m1, m2, m3):
        Student.rn = rn
        Student.name = name
        Student.marks.append(m1)
        Student.marks.append(m2)
        Student.marks.append(m3)
    
    def displayData(self):
        print("Roll Call Number: ", Student.rn)
        print("Name is: ", Student.name)
        print("Grade in subject 1: ", Student.marks[0])
        print("Grade in subject 2: ", Student.marks[1])
        print("Grade in subject 3: ", Student.marks[2])
        print("Average Grade of: ", self.average())
        GradeAverage = self.average()
        if (GradeAverage > 90):
            print("your an A student")
        elif (GradeAverage > 80):
            print("your a B Student")
        else:
            print("do better")
    
    def total(self):
        m = Student.marks
        return(Student.marks[0] + Student.marks[1] +Student.marks[2])
    
    def average(self):
        return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)

r = int (input("Enter the roll call number: "))
name = input("Enter the name: ")
m1 = int (input("Enter the Grade in first subject: "))
m2 = int (input("Enter the Grade in second subject: "))
m3 = int (input("Enter the Grade in third subject: "))

s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()
Roll Call Number:  26
Name is:  Derek Sol
Grade in subject 1:  81
Grade in subject 2:  84
Grade in subject 3:  93
Average Grade of:  86.0
your a B Student

Unit 3 Sections 14-15

Notes

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.

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.

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.

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

Homework

import random

n = int(input("How many numbers would you like to generate?"))
a = int(input("Give the lowest number you want all numbers to be picked from?"))
b = int(input("Give the highest number you want all numbers to be picked from?"))
numbers = [random.randint(a, b) for _ in range(n)]
# I input the range from numbers 1-100

evens = []
odds = []
for number in numbers:
    if number % 2 == 0:
        evens.append(number)
    else:
        odds.append(number)

print(evens)
print(odds)
[46, 78, 12, 78, 76, 8, 18, 92, 98, 42, 64, 30]
[83, 95, 7, 97, 39, 61, 73, 21]
import numpy as np

poly = np.poly1d([2, 0, 0, -6, 24, 0])

derivative = poly.deriv()

print("The derivative of \n" + str(poly) + "\n" + "is" + "\n" + str(derivative))
The derivative of 
   5     2
2 x - 6 x + 24 x
is
    4
10 x - 12 x + 24
import numpy as np

n = np.poly1d([13, 0, 4, 0, 0])

d = np.poly1d([2])

derivative = ((d * n.deriv()) - (d.deriv() * n)) / 4

result = derivative(9)


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

When x = 9,  f'(x) = 
18990
import random

animals = ['dog1', 'dog2', 'dog3', 'dog4', 'dog5', 'dog6', 'dog7', 'dog8', 'dog9', 'dog10', 'cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7', 'cat8', 'cat9', 'cat10']

random.shuffle(animals)

print(animals)
['dog10', 'cat8', 'cat4', 'dog3', 'cat1', 'dog1', 'cat10', 'dog2', 'cat6', 'dog6', 'dog4', 'dog7', 'cat2', 'dog5', 'cat9', 'cat7', 'dog9', 'cat5', 'dog8', 'cat3']

Two Other Python Libraries

Keras

  • Keras is a deep learning API written in Python, running on top of the machine learning platform TensorFlow. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result as fast as possible is key to doing good research.
  • It is simple, flexible, and powerful.
  • Keras reduces developer cognitive load to free you to focus on the parts of the problem that really matter.
  • Keras adopts the principle of progressive disclosure of complexity: simple workflows should be quick and easy, while arbitrarily advanced workflows should be possible via a clear path that builds upon what you've already learned.
  • Keras provides industry-strength performance and scalability: it is used by organizations and companies including NASA, YouTube, or Waymo.

Pandas

  • Pandas is an open source Python package that is most widely used for data science/data analysis and machine learning tasks. It is built on top of another package named Numpy, which provides support for multi-dimensional arrays. -Pandas makes it simple to do many of the time consuming, repetitive tasks associated with working with data such as; data cleansing, data fill, data normalization, merges and joins, data visualization, statistical analysis, data inspection, loading and saving data, etc.
  • Pretty much used to analyze data fast, powerfully, and flexibly

Unit 3 Sections 16

Notes

What is a simulation?

  • A simulation is a tested scenario used for viewing results/outputs to prepare for them in real world situations
  • These can be used for games like dice rolling, spinners, etc
  • These can be used for practical things such as building structures, testing car crashes, and other things before engaging in them in the real world
  • These simulations can have the option of obeying real world physics (Gravity, collision) or they can go against these norms since this is a fictitious scenario, and couldn't happen in real life

Simulations in Real Life

  • Simulations are used extremely frequently in real life applications. One of the most common examples of simulations are video games. A games physics engine can accurately simulate objects colliding
  • Another example is Blender, the software used in 3d animations class, here at Del Norte. Blender is made up of many small simulations, but one big one it uses is simulating the way light bounces off of and interacts with objects.

Homework

import time

# Define a function that updates the simulation
def update_simulation():
  # Update the state of the simulation here...
  
  # Prompt the user to enter the mass and radius of a planet
  mass = float(input("Enter the mass of the planet (in kilograms): "))
  radius = float(input("Enter the radius of the planet (in kilometers): "))
  
  # Calculate the gravity of the planet
  gravity = (6.67 * 10**-11 * mass) / (radius**2)
  print(f"Gravity of planet: {gravity}")
  #Gravity of planet 1: Neptune
  #Gravity of planet 2: Saturn
  #Gravity of planet 3: Jupiter
  #Gravity of planet 4: Uranus

# Run the simulation indefinitely
while True:
  update_simulation()
  time.sleep(1) # Pause for 1 second between each update
Gravity of planet: 29180968.4670602
Gravity of planet: 28951451.382520344
Gravity of planet: 67089129.85402547
Gravity of planet: 23315153.5014559
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb Cell 57 in <cell line: 21>()
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=13'>14</a>   #Gravity of planet 1: Neptune
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=14'>15</a>   #Gravity of planet 2: Saturn
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=15'>16</a>   #Gravity of planet 3: Jupiter
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=16'>17</a>   #Gravity of planet 4: Uranus
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=17'>18</a> 
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=18'>19</a> # Run the simulation indefinitely
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=19'>20</a> while True:
---> <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=20'>21</a>   update_simulation()
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=21'>22</a>   time.sleep(1)

/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb Cell 57 in update_simulation()
      <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=3'>4</a> def update_simulation():
      <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=4'>5</a>   # Update the state of the simulation here...
      <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=5'>6</a>   
      <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=6'>7</a>   # Prompt the user to enter the mass and radius of a planet
----> <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=7'>8</a>   mass = float(input("Enter the mass of the planet (in kilograms): "))
      <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=8'>9</a>   radius = float(input("Enter the radius of the planet (in kilometers): "))
     <a href='vscode-notebook-cell:/Users/dmsol/Tera/_notebooks/2022-12-15-STP.ipynb#Y113sZmlsZQ%3D%3D?line=10'>11</a>   # Calculate the gravity of the planet

ValueError: could not convert string to float: ''

Example of a Simulation

In terms of coding, NBA 2K is a simulation because it uses a computer program to simulate the behavior and interactions of the various elements that make up a game of basketball. This includes the players, the ball, the court, and the rules of the game. To create this simulation, the developers of NBA 2K use a combination of algorithms, data structures, and mathematical calculations to model the behavior of these elements. For example, they may use algorithms to simulate the movement of the ball and the players on the court, and use data structures to store information about the teams, players, and game rules. Additionally, the developers may use mathematical calculations to model the physics of the game, such as the effects of gravity on the ball and the players, and the interactions between different objects on the court.

Unit 3 Sections 17-18

Notes

What is Algorithmic Efficiency?

  • The ability of an algorithm to solve a problem in an efficient way
    • An efficient algorithm solves a problem quickly and with a minimum amount of resources, such as time and memory.
  • How do we determine if an algorithm is efficient or not?
    • One way we can do this is by determining the time complexity of the algorithm.
    • Another way is through space complexity. ### Heuristic solution
    • An heuristic solution is an approach to a problem that produces a solution that isn't necessarily optimal but can be used when normal methods take forever.

Decidable problem vs Undecidable problem

  • A decidable problem is a problem in computer science and mathematics for which an algorithm can be created that can always produce a correct answer or solution. In other words, a decidable problem is a problem for which there exists an algorithm that can be used to determine whether a given input is a valid solution or not.
  • An undecidable problem problem is a problem in computer science and mathematics for which it is impossible to create an algorithm that can always provide a correct answer or solution. This means that it is not possible for an algorithm to always determine whether a given input is a valid solution to an undecidable problem.

The Halting Problem

The halting problem is an example of an undecidable problem. It states that it is not always possible to correctly determine whether a code halts or runs forever.

  • There is no way to write an algorithm to analyze and determine whether a body of code can run forever or not.

Homework

Traveling Merchant Problem Hacks:

What did you and your team discuss? (record below)

We discussed all the possible ways to start from Indianapolis and visit all the cities. We said that in order to get the shortest route, you have to take the shortest flight first, so go cincinnati, then figure out the shortest distances from there and continue on.

Describe the method used to solve the traveling merchant problem. (record below)

The method used was a heuristic solution. We go to the shortest travel from Indianapolis, then look at the neighboring cities. We continue to pick the shortest travel every time and follow that until the end. This makes the traveling more optimal with less distance traveled and less time consuming if it were to be a real life scenario.

Hacks

Come up with one situation in which a computer runs into an undecidable problem. Explain why it is considered an undecidable problem.

One situation in which a computer may run into an undecidable problem is when it is trying to determine whether a given mathematical statement is true or false. This problem, known as the axiomatic truth problem, is considered undecidable because there is no algorithm that can accurately determine the truth value of an arbitrary mathematical statement. The reason the axiomatic truth problem is undecidable is that it involves trying to determine the truth or falsity of an arbitrary statement, which may be impossible to do with complete accuracy. In mathematics, a statement is considered true if it can be proven to be true using a set of axioms and rules of inference. However, it is not always possible to prove the truth or falsity of a given statement using these methods. For example, the statement "There are infinitely many prime numbers" cannot be proven or disproven using the standard axioms of mathematics.

import time

def linear_search(lst, x):
    start_time = time.perf_counter_ns() # records time (nanoseconds)
    for i in range(len(lst)): # loops through the entire list 

        if lst[i] == x: # until the x value we are looking for is found
            end_time = time.perf_counter_ns() # records time again
            total_time = (end_time - start_time) // 1000 # subtracts last recorded time and first recorded time
            print("Found element after {} loops in {} microseconds".format(i+1, total_time)) # prints the results
            return print("Your number was found at", i)
            
    end_time = time.perf_counter_ns() # records the time again
    total_time = (end_time - start_time) // 1000 # subtracts last recorded time and first recorded time
    print("Element not found after {} loops in {} microseconds".format(len(lst), total_time)) # prints the results
    return "Your number wasn't found :("


lst = list(range(1, 10001)) # list with numbers 1-10000

x = 5500 # replace with an integer between 1 and 10000 (I suggest big numbers like 500, 2000, so on)

linear_search(lst, x) # runs procedure
Found element after 5500 loops in 372 microseconds
Your number was found at 5499
import time 

def binary_search(lt, x):
    start_time = time.perf_counter_ns() # starts timer
    low = 0 # sets the lower side 
    mid = 0 # sets mid value
    high = len(lt) -1 # sets the higher side
    num_loops = 0 # number of loops the search undergoes to find the x value

    while low<=high: # Loop ran until mid is reached
        num_loops += 1 # adds one loop each time process is repeated
        mid = (low + high) // 2 # takes the lowest and highest possible numbers and divides by 2 and rounds to closest whole #

        if lt[mid] == x:
            end_time = time.perf_counter_ns() # records time
            total_time = (end_time - start_time) // 1000 # time in microseconds
            print("Element found after {} loops in {} microseconds".format(num_loops, total_time)) # prints the results
            return mid # returns the index value

        elif lt[mid] > x: # if mid was higher than x value, then sets new highest value as mid -1 
            high = mid -1 

        elif lt[mid] < x:
            low = mid + 1 # if mid was lower than x, sets the new low as mid + 1
            
    end_time = time.perf_counter_ns()
    total_time = (end_time - start_time) // 1000 
    print("Element not found after {} loops in {} microseconds".format(num_loops, total_time)) # prints the results
    return "Your number wasn't found :("


lt = list(range(1, 10001)) # list with numbers 1-10000

x = 55# replace with an integer between 1 and 10000 (I suggest big numbers like 500, 2000, so on)

binary_search(lt, x) # runs procedure
Element found after 12 loops in 6 microseconds
54

Graphs on Review Ticket

Link to see the Graphs/ReviewTicket

Looking at the graphs, even though both graphs contained the same x values, the 1st code gave me much higher values in microseconds(y) than the 2nd code. Therefore, the 2nd graph and code is more efficient. This is because it is finding the element in an overall less time(in microseconds) than the 1st graph.

Decidable Problem

def find_smallest_odd(n):
  # Set the smallest odd number to 1
  smallest_odd = 1
  
  # Set the current number to 1
  current_num = 1
  
  # Loop until the current number is greater than n
  while current_num <= n:
    # If the current number is odd, update the smallest odd number
    if current_num % 2 == 1:
      smallest_odd = current_num
      
      # Break the loop since we have found the smallest odd number
 
    break
      
    # Increment the current number
    current_num += 1
    
  # Return the smallest odd number
  return smallest_odd
find_smallest_odd(20) #Since the smallest odd number that is less than or equal to 20 is 1, the output will be 1

Code that runs forever

def is_prime(n):
  # Check if the number is less than 2, which is not considered prime
  if n < 2:
    return False
  
  # Check if the number is divisible by any number less than itself
  for i in range(2, n):
    if n % i == 0:
      return False
      
  # If the number is not divisible by any number less than itself, it is prime
  return True

# Set the current number to 2, which is the smallest prime number
current_num = 2

# Set a flag to indicate whether the current number is prime
is_prime = True

# Loop indefinitely
while True:
    
  current_num += 1