Week 2 Notes
3.8 to 3.10 Notes
Iteration: a repeating portion of an algorithm, repeats a specified number of times or until a given condition is met.
Iteration Statements: change the sequential flow of control by repeating a set of statements zero or more times, until a stopping condition is met
Repeat Until: if the condition evaluates to true initially, the loop body is not executed at all, due to the condition being checked before the loop.
Stopping conditions can stop an interaction if it was already met.
Definition: Iteration Statement - cause statements to be executed zero or more times, subject to some loop-termination criteria
range function gives the range for the variable
a = 1
for a in range(2,10):
print(a)
Breaking statements can also be used to break a loop. Conditions can be constantly used in lists that are not numbers.
animals = ["dog", "cat", ]
for i in animals:
if i == "fish":
break
print(i)
# Make piece of code that gives three different recommendations for possible classes to take at a school based on two different conditions. These conditions could be if the student likes STEM or not.
stem = ["Biology", "Math", "Engineering"]
notstem = ["pe", "offrole"]
love = ["Alex", "Daniel"]
dislike = ["kim", "elliot"]
list = [love, dislike]
for item in list:
if item in love:
print(stem)
elif item in dislike:
print(notstem)
List Operations: write expressions that use list indexing and list procedures.
Traversing Lists: all elements in the list are assessed, or a partial traversal, where only a portion of elements are accessed (can be complete).
Complete Traversal: All elements in a list are assessed Partial Traversal: Only a given portion of elements are assessed Iterative Traversal: When loops are used to iterate through a list and to access each single element at a time.
- insert( ) allows a value to be inserted into a list at index i
- append( ) allows a value to be added at the end of a list
- remove( ) allows an element at index i to be deleted from a list
- length( ) returns the number of elements currently in a specific list
3.9 and 3.11 Algorithms
Three components of an Algorithm:
- Selection
- Sequence
- Iteration
Algorithms can be written in different ways and still create the same thing.
It is important to notice the differences in the algorithms to see if there are any errors that can occur
Tommy and Billy are working on solving the same issue with an algorithm
Tommy creates a functioning code and yells "I did it!"
He looks over at his friend Billy which is having a bit of trouble and he offers help
However, Billy's code looks basically the same! which confuses them
Then they remember that they were taught that algorithms that look similar don't always have the same results and they collaborate to do further investigation:)
print("What Grade Did You Get?")
grade = int(input("Enter Grade:"))
A = grade >= 90
B = 70 <= grade < 90
C = grade < 70
if A:
print("Wow! Good job!")
elif B:
print("Nice!")
elif C:
print("Do Better")
The code above does look different from the first two, but it is the same thing, where instead of the number being identified, it is being identified through the letter that it is given. Does the same thing, but uses a different method to find said grade.
Developing Algorithms
When creating an algorithm, it is good to outline its process before coding to ensure that it is sequenced correctly (the steps taken to derive your answer)
- Visualization helps one see the flow of the whole algorithm
- More efficient and effective
Algorithms with iteration repeat functions until a goal is fulfilled.
Algorithms with selection will only go through certain functions if certain things are true or false
An example of visualization is shown below
- Start
- Input number of hours parked
- If hours is less than 1, cost is free
- If hours is between 1 and 2, cost is $5
- If hours is between 2 and 3, cost is $8
- If hours is between 3 and 4, cost is $10
- If hours is more than 4, cost is $12
- Display cost and goodbye
- Finish
print("The parking rate is as follows: \n Less than one hour: Free \n 1-2 hours: $5 \n 2-3 hours: $8 \n 3-4 hours: $10 \n 4+ hours: $12")
time = float(input("How many hours have you parked at this garage?"))
print("How many hours have you parked at this garage?")
print(time, "hours costs:")
if time < 1 :
print("Free")
elif time >= 1 and time < 2 :
print("$5")
elif time >= 2 and time < 3 :
print("$8")
elif time >= 3 and time < 4 :
print("$10")
else:
print("$12")
print("Have a good day!")
Notice how the algorithm is planned out before creating, making it more efficient and less prone to errors.
To use preexisting algorithms, knowing some can help construct new ones
- simple existing algorithms include determining the min and max of 2+ numbers
- Computing sum or average
- identifying if an integer is even or odd
- Using existing algorithms structures can help as building blocks to reduce the time to develop, testing, and errors.
Binary Search
- The binary search algorithm starts at the middle of a sorted data set of numbers and eliminates half of the data; this process repeats until the desired value is found or all elements have been eliminated. However, data must be sorted order to use this algorithm (set of instructions to solve something)
- Binary searching is oftentimes more efficient than sequential/linear search when applied to sorted data.
Computers line up values in order and search sequentially down the line, one at a time. This is called a sequential search because each element in a list is examined starting with the first element until we find the desired target or reach the end of the list. The elements do not need to be in any order to do a sequential search. If you are searching for a number in the middle of 7 values, it would take four comparisons to find it.
Steps for Binary Search
1. Start by placing the numbers in order (ascending or descending, both work).
2. Look at the middle number first
3. The middle number is determined by taking the highest index (the order of it) number and the lowest and divide by two. If we have 7 numbers placed in order, the first and last's places are added together, so 1+7/2 = 4. If the number is greater than the middle it will take the middle of the middle index and last index and will continue in this process.
This is similar to Divide and Conquer If you have 600 sorted numbers. you would go in this process 600/2 = 300(middle) 300/2 = 150 150/2 = 75 (Always round up) 75/2 = 38 19/2 = 10 5/2 = 3 3/2 = 2 2/2 = 1 <-- the answer
You can also conduct a binary search on lists with words in alphabetical order. For example,
Fruit = ["Apple", "Banana" , "Kiwi", "Mango" , "Strawberry"] To find Mango you need to go to the middle and look at Kiwi and then Mango second, it is the arithmetic of the index number that will determine the element you are looking at.
3.12 and 3.13
procedure: a named set of instructions that can take in parameters and return values. It can also be called method or function in different programming languages.
Parameter: independent variables used in the procedure to produce a result It allows a procedure to execute without initially knowing specific input values
Return Function in Python
To determine the result of a procedure or any code, you must follow the code line by line and see what each one does
Using syntax, you can determine the result by
function parameters return value and statements To use return values, you have to write the syntax return followed by the expression you would like to return var A return statement exits a function and instructs python to continue executing the program and to return a certain value
Value can be string, a tuple, or any other type that is being sent back to the main program
Ex:
We use the Return function will assign the values for the variables. Try it below with and without the return result. The code basically defines the function as find_cube(num), but in order for it to update it the result, we use the return (variable) for it
return ("what is being called, in this case the result")(this is also called the parameter)
def find_cube(num):
result = bin(num * num * num)
return result
cube = find_cube(3)
cube2 = find_cube(4)
print('Cube:',cube)
print('Cube:',cube2 )
- Modularity - the practice of breaking a complex program into smaller, independent parts or modules that can be used and reused in different parts of the program
- Abstraction - the practice of hiding the details of how a particular code or system works and exposing only the essential features or functions that are necessary for other parts of the program to use
- Duplication - having multiple duplicate code blocks, often decreasing readability and efficiency
- Logic - the sequence of steps and operations that a computer follows to
Parameters are used to manage complexity calling functions with procedure names
Vocab
- Procedure: a module of code that is created to complete a certain tasks, also known as a function
- Procedure Name: the name that is given to the function/procedure
- Parameter: a variable (independent) that is used in a function to allow for data to be important into said function
- Arguments: A way to provide information to a function usually defined outside a function and then important into a function with parameters.
Example Below:
def function(a,b): # function is defined
print(a+b) # prints output of variables
function(1,2) # one instance that it can be used
function(2,3) # another instance
3
5
a and b are the parameters
def InchestoFeet(inches):
Feet = inches/12
return Feet
result = InchestoFeet(24)
print(result)
Vocab for the Week 2
Bits, Bytes, Hexadecimal / Nibbles
- Bits - A given byte contains either bits or a code. A designation of 'bits' means that each individual bit has its own meaning, independent of the meaning of other bits in the byte.
- Byte - code is computer object code that an interpreter converts into binary machine code so it can be read by a computer's hardware processor.
- Hexadecimal - relating to or using a system of numerical notation that has 16 rather than 10 as its base.
- Nibble - a nibble is four consecutive binary digits or half of an 8-bit byte.
Unsigned Integer, Signed Integer, Floating Point
- Unsigned Integer - Unsigned Integers (often called "uints") are just like integers (whole numbers) but have the property that they don't have a + or - sign associated with them
- Signed Integer - A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647].
- Floating Point - There are two floating point primitive types. Data type float is sometimes called "single-precision floating point". Data type double has twice as many bits and is sometimes called "double-precision floating point".
Binary Data Abstractions: Boolean, ASCII, Unicode, RGB
- Boolean - True or False statements
- ASCII - ASCII (American Standard Code for Information Interchange) is the most common character encoding format for text data in computers and on the internet.
- Unicode - an international encoding standard for use with different languages and scripts, by which each letter, digit, or symbol is assigned a unique numeric value that applies across different platforms and programs.
- RGB - Red Green Blue (Gamer)
Data Compression: Lossy, Lossless (note discussed yet)
- Lossy - Lossy is a data encoding and compression technique that deliberately discards some data in the compression process.
- Lossless - With lossless compression, every bit of data originally in a file remains after it is uncompressed, and all the information is restored