AP CSP Tri 2 Portfolio
AP Exam Content and Vocab
- 3.1-3.2 Variables, Assignments, and Data Abstractions
- 3.3-3.4 Mathematical Expressions and Strings
- Unit 3 Section 5-7
- 3.9-3.11 Algorithms and Binary Search
- 3.9-3.11
- 3.12-3.13
- 3.14-3.15 Libraries and Random Values
- 3.17-3.18 Undecidable Problems
# String
name = "table1"
print(name, type(name))
# Integer
number = 4
print(number, type(number))
# Booleans
isAbsent = False
print(isAbsent, type(isAbsent))
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))
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))
3.3-3.4 Mathematical Expressions and Strings
An algorithm: a set of instructions that can accomplish a specific task
- Sequencing: Algorithms do taks in the order of specification
- Selection: Helps choose two different outcomes based off a decision
- 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))
Flowcharts: The use shapes and arrows to represent the steps of an algorithm
num1 = 10
num2 = num1 -25
num3 = 100*num1
num4 = num1/num2
num5 = 9 % num4
print(num5)
Order of operations in programming are performed in the same order as operations in mathematics.
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)
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%")
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)
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")
Nested Conditional statements consist of conditional statements within other conditional statements
- utilizes if else statements within if else statements
- basics of a nested conditional
fruits = ["apple", "grape", "strawberry"]
print (fruits)
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])
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
ELSEREMOVE(words, index)
Display(words) This will output "unusual", "bold", "away"index <- index + 1
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)
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!")
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)
Flowchart: Flowcharts can help you visualize the functionality of a program
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")
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)
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")
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")
- 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))
- 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)
- 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.
- 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 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)
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))
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")