3.1-3.2 Variables, Assignments, and Data Abstractions

Variable: an abstraction inside a program that can hold a value

  • Types of Variables
  • Integer: A number
  • Text/String: A word
  • Boolean: Data that determines if something is true or false
# String
name = "table1"
print(name, type(name))

# Integer
number = 4
print(number, type(number))

# Booleans 
isAbsent = False
print(isAbsent, type(isAbsent))
table1 <class 'str'>
4 <class 'int'>
False <class 'bool'>

Data Abstraction is a method used in coding to represent data in useful form, by taking away aspects of data that aren't being used in the situation

  • List = ordered sequence of elements
  • element = individsual 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)
def Reverse(lst):
    new_lst = lst[::-1]
    return new_lst

lst = ["pink", "green", "purple", "yellow", "orange", "blue", "black"]
print(Reverse(lst))
['black', 'blue', 'orange', 'yellow', 'purple', 'green', 'pink']

Managing Complexity is improving code readability and efficiency

  • Lists can be used to manage complexity
colorList = ["green", "red", "pink", "purple", "blue", "brown"]

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

3.3-3.4 Mathematical Expressions and Strings

An algorithm: a set of instructions that can accomplish a specific task

  1. Sequencing: Algorithms do taks in the order of specification
  2. Selection: Helps choose two different outcomes based off a decision
  3. Iteration: If a conditions is true, then the code can repeat
def Reverse(lst):
    new_lst = lst[::-1]
    return new_lst

lst = ["pink", "green", "purple", "yellow", "orange", "blue", "black"]
print(Reverse(lst))
['black', 'blue', 'orange', 'yellow', 'purple', 'green', 'pink']

Flowcharts: The use shapes and arrows to represent the steps of an algorithm

reverser

Basic Operations

Subtraction:

  • represented by "-"

Addition:

  • represented by "+"

Multiplication

  • represented by "*"

Division

  • represented by "/"

Getting the Remainder represented by "MOD" (% in python)

num1 = 10
num2 = num1 -25
num3 = 100*num1
num4 = num1/num2
num5 = 9 % num4
print(num5)
-0.3333333333333328

Order of operations in programming are performed in the same order as operations in mathematics.

Strings

A string is a collection of characters. Can be numbers, letters, spaces, special symbols, etc. String concatenation is combining two or more strings to make a new strings in order to create a new string A substring is a part of and already existing string.

cookie = "choclate" 
cookie2 = "rasin" 
len1 = len(cookie) / 2 
len1 = str(len1)
len2 = len(cookie2) * 45
len2 = str(len2) 
vote1 = cookie + " vote: " + len2 
vote2 = cookie2 + " vote: " + len1 
votes = vote1 + " " + vote2 
print(votes)
choclate vote: 225 rasin vote: 4.0

Unit 3 Section 5-7

A boolean is a data type with two possible values: true or false\ Relational operators could use operators to determine if the average of 5 grades is greater than 80

gradeList = [90, 65, 60, 75, 95]

averageGrade = sum(gradeList)/len(gradeList)

if averageGrade > 80:
    print("the average grade is" + averageGrade + "%")
else:
    print("The average grade is below 80%")
The average grade is below 80%

Logical Operators are similar to relational operators but these operators don't necessarily deal with equivalent/non-equivalent values, but they rather work on operands to produce a singular boolean result

  • AND: returns TRUE if the operand around it are TRUE
  • OR: returns TRUE if at least one operand is TRUE
  • NOT: returns TRUE if the following boolean is FALSE
print("1 > 2 or 5 < 12:", 1>2 or 5 < 12)

# NOT function
print("24>8:", not 24>8)

# AND function
print("10>20:", 10>20 and 20<10)
1 > 2 or 5 < 12: True
24>8: False
10>20: False

Selection: uses a condition that evaluates to true or false Algorithm is a finite set of instructions that accomplish a specific task

x=20
y=10
if x>y:
    print("x is greater than y")
else: 
    print("x is not greater than y")
x is greater than y

Nested Conditional statements consist of conditional statements within other conditional statements

  • utilizes if else statements within if else statements
  • basics of a nested conditional

Screenshot 2022-12-11 221853

3.9-3.11 Algorithms and Binary Search

Lists

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
fruits = ["apple", "grape", "strawberry"]
print (fruits)
['apple', 'grape', 'strawberry']
brands = ["nike", "adidas", "underarmour"]
numbers = [1, 2, 3, 4, 5]
truefalse = [True, False, True]

Lists are just one of four 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

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
fruits = ["apple", "grape", "strawberry"]
index = 1
print (fruits[index])
grape

Methods in Lists

append() - adds elements to the end of the list insert() - adds element at given position reverse() - reverses the lsit order count() - returns the amount of elements with the specified value clear() - removes the elements from the list

Try this

  • Determine the output of the code segment words <- "old", "car", "unusual", "new", "bold", "far", "away" index <- 1 FOR EACH word IN words If LEN(word) = 3
      REMOVE(words, index)
    
    ELSE
      index <- index + 1
    
    Display(words) This will output "unusual", "bold", "away"

Iteration

Iteration allows you to go back in a certain value within a list

  • it is important for time and sanity
  • formally, Iteration is the repetition of a process or utterance applied to the result or taken from a previous statement.

Iteration statements

  • 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
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()
output = ""

for letter in inp:
    for word in words:
        if letter == word[0]:
            output += word + " "

print(inp + "\n" + output)
bruh
bravo romeo uniform hotel 

3.9-3.11

An algorithm is a process or set of rules to be followed through CODE. There are set limitations, this is what makes algorithms fun, you can use your own imagination and create whatever you want with your instructions.

temp = int(input("Select a temperature from 0 to 99 degrees F"))
if (temp >= 90):
    print("It's too hot outside!")
else:
    if (temp >= 65):
        print("Sure I will play outside!")
    else: 
        print("It is too cold outside!")
It's too hot outside!

Conditions vs Booleans

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.

IsHoliday = False
IsWeekday = True
if IsHoliday:
    driveWork = True
else: 
    if IsWeekday: 
        driveWork = True
    else: 
        driveWork = False
print(driveWork)
True

Flowchart: Flowcharts can help you visualize the functionality of a program

reverser

Selection: A process used in algorithms where a conditional if-statements leads to one of two outcomes

print("choose value for x")

varx=int(input("Enter any positive Integer"))

if (varx %2 == 0):
    print("the number is even")

else:
    print("the number is odd")
choose value for x
the number is even

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
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()
output = ""

for letter in inp:
    for word in words:
        if letter == word[0]:
            output += word + " "

print(inp + "\n" + output)
whatever
whiskey hotel alfa tango echo victor echo romeo 

What is Binary Search?

  • Binary search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
  • An algorithm for iterating to find a value inside a data set
def BinarySearch(array, x, low, high):

    # Repeat until the pointers low and high meet each other 
    while low <= high:

        mid = low + (high - low)//2 # find the middle (taking the higest index number plus the lowest and divided by two)

        if array[mid] == x: # if desired number is the middle is found return desired number (middle number) 
            return mid

        elif array[mid] < x: 
            low = mid + 1

        else:
            high = mid - 1

    return -1


array = [3, 4, 5, 6, 7, 8, 9]
x = 4

result = BinarySearch(array, x, 0, len(array)-1)

if result != -1:
    print("Element is present at index " + str(result))
else:
    print("Not found")
Element is present at index 1

3.12-3.13

  • A procedure is a named group of programming instructions that may have parameters and return values.
  • Parameters are input values of a procedure. Arguments specify the values of the parameters when procedure is called.
print("choose value for x")

varx=int(input("Enter any positive Integer"))

if (varx %2 == 0):
    print("the number is even")

else:
    print("the number is odd")
choose value for x
the number is even
  • 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
    • manages complexity in a program
  • Simply, procedural abstraction is naming and calling a prewritten procedure
def letterGradeCalculator(percent):
    if (percent < 60):
        return "F"
    elif (percent >= 60) and (percent < 70):
        return "D"
    elif (percent >= 70) and (percent < 80):
        return "C"
    elif (percent >= 80) and (percent < 90):
        return "B"
    elif (percent >= 90) and (percent < 100):
        return "A"
    else:
        return "A+"

percent = int(input("What is your percent grade?"))
print(percent)
print(letterGradeCalculator(percent))
92
A
  • Subdivision of a program into separate subprograms is called modularity
Code Segment 1 Code Segment 2
ROTATE_LEFT() detourLeft()

MOVE_FORWARD()|turnCorner()| ROTATE_RIGHT |MOVE_FORWARD()| MOVE_FORWARD()|MOVE_FORWARD()| MOVE_FORWARD() ROTATE_RIGHT() MOVE_FORWARD() ROTATE_LEFT() MOVE_FORWARD() ROTATE_LEFT() MOVE_FORWARD() MOVE_FORWARD MOVE_FORWARD()

3.14-3.15 Libraries and Random Values

  • 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.
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]]
  • 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.

Screenshot 2022-12-11 221853

  • 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.

CollegeBoard

  • 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
import random 

n = 1
sum = 0
while n > 0:
    sum = sum + random.randint(1 , 6)
    n = n - 1
    break
n = 0
    
print(sum) 
6

3.17-3.18 Undecidable Problems

Algorithmic Efficiency - the ability of an algorithm to solve a problem in an efficient way

Decision Problem - a problem in computer science and mathematics that can be solved by a yes-no answer, also known as a binary answer.

Decidable Problem - a problem in computer science and mathematics for which an algorithm can be created that can always produce a correct answer or solution.

Undecidable Problem - 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.

def divideThirteen(number):
    if number % 13 == 0:
        return True
    else:
        return False

print(divideThirteen(26))
print(divideThirteen(30))
True
False
i = 0
number = 1
def integerTest(n):
    # Testing if the number is an integer
    if n%1 ==0:
        return True
    else:
        return False
# Using while loop to keep searching an a non-integer above 1. Note that the computer runs forever.
while i == 0:
    number += 1
    if integerTest(number) == False:
        i +=1
        print("Done")