Unit 3 Sections 3-4 Notes
Algorithm
An Algorithm is a set of instructions that can accomplish a specific test
Types of Algorithms
- Sequencing: Algorithms do tasks in the order of specification.
- Selection: Helps choose two different outcomes based off a decision.
- Iteration: If a condition is true, then the code can repeat.
Ways to represent Algorithms
- Flowcharts: Shapes and arrows represent steps of an algorithms
- Pseudocode: Human language + code language
Addition
num1 = 2 + 1
Subtraction
num1 = 2 - 1
Multiplication
num1 = 2 * 1
Division
num1 = 2 / 1
Remainder
num1 = 5 % 2
Other examples such as numbers or variables
num1 = 10
num2 = num1 - 25
num3 = 100 * num1
num4 = num1 / num2
num5 = 9 % num4
num1 = 9 % 2 * ( 8 - 2 ) + 8 / ( 6 - 4 )
print(num1)
score = 0 # 1
score = newScore # 2
score = newScore + 2 # 3
avgScore = allscores(20, 60, 80) # 4
Changing the order of the steps changes the overall outcome, since every time the value assigned to a variable is changed, it overrides the last value which was assigned to the same variable. That is why it is important to track the value of variables, especially in code where the value is constantly changing.
num1 = 2
num2 = 4
num3 = 6
num1 = num2 + num3 # num1 is now 4 + 6, which is 10
num2 = num1 + num3 # num2 is now (the new num1) 10 + 6, which is 16
# output: num1 = 10, num2 = 16, num3 = 6
vs
num1 = 2
num2 = 4
num3 = 6
num2 = num1 + num3 #num2 is now 8
num1 = num2 + num3 # num1 is now 14
# output: num1 = 14, num2 = 8, num3 = 6
Tracking variables is a common question found on AP exams and is an important thing to keep in mind when writing any code. If the value of your variables changes a lot, not accounting for these changes can result in an unwanted outcome.
var1 = 9
var2 = 7
var3 = 2
#var = var1 + 5
#var2 = var1 - var3
#var1 = var2
#var3 = (var1 + var2) / 2
#var2 = 6
print(var1)
print(var2)
print(var3)
Num1 = 50
Num2 = Num1 % 9 + 15 # 50/9 = 45 R5, 5+15 = 20
Num3 = Num2 / Num1 + ( Num2 * 2 ) # 20/50 + (20*2) = 40.4
Num4 = Num3 + Num1 / 5 - 10 # 40.4+50 / 5-10 = 40.4
Result = Num4 - Num2 # 40.4-20 = 20.4
The answer for Num4 - Num2 = 20.4
Num1 = 10
Num2 = Num1 % 3 * 4 # 10/3 = R1, 1*4 = 4
Num1 = Num2 # Num1 = 4
Num3 = Num1 * 3 # Num3 = 4, 4*3 = 12
Result = Num3 % 2 # 12 % 2 = 0
The answer for Num3 % 2 = 0
valueA = 4
valueB = 90
valueC = 17
valueB = valueC - valueA # valueB = 17 - 4 = 13
valueA = valueA * 10 # 4 * 10 = 40
if valueB > 10:
print(valueC)
type = "curly"
color = "brown"
length = "short"
type = "straight"
hair = type + color + length # straight + brown + short
print(hair)
Noun = "Mr.Mortenson"
Adjective = "handsome"
Adjective2 = "Very"
Verb = "is"
abrev = Noun[0:6]
yoda = (Adjective2 + " " + Adjective + " " + abrev + " "+ Verb + ".")
print(yoda)
bagel = "blueberry"
bagel2 = "rasin"
len1 = len(bagel) / 2
len2 = len(bagel2) * 45
vote1 = bagel + "vote" + str(len2)
vote2 = bagel2 + "vote" + str(len1)
votes = vote1 + " " + vote2
print(votes)