Class Lesson Hacks
- Lessons 1 and 2
- Lessons 3 and 4
- Lessons 5, 6, and 7
- Lessons 8 and 10
- Lessons 9 and 11
- Lessons 12 and 13
- Lesson 14 and 15
- Lesson 16
- Lesson 17 and 18
Lessons 1 and 2
Notes:
- A variable is an abstraction inside a program that holds a value, where each variable has associated data storage that represents a single value at a time (However, if the value is a collection type such as a list, then the value can contain multiple values).
- Variables can be seen as "containers" and each container has a name that holds what it is supposed to hold.
- Variables have different data types that store specific kinds of data depending on what is being represented.
Hacks 1 D1
Questions (College Board's Essential Knowledge):
- What exactly IS a variable?
- A variable is an abstraction inside a program that holds a value, where each variable has associated data storage that represents a single value at a time.
- What is the best data type to represent someone's dog's name?
- A string
- Why is it important to give variables specific names before containing values?
- So that they have an appropriate name to the value which will be contained.
- What is the best way to represent someone's phone number?
- The best way is to use a string to make sure the numbers don't interfere with the code.
Bonus (Not required but important to know):
- How can we update a variable's value
- Using + or - for incrementing or decrementing
- What function is used to receive a user's input?
- input()
Hacks 2 D1
Answer these:
- In your own words, briefly explain by writing down what an assignment operator is
- The assignment operator is the equal sign (=) which allows to assign elements of code to a value.
- In Collegeboard pseudocode, what symbol is used to assign values to variables?
- <--
- A variable, x, is initially given a value of 15. Later on, the value for x is changed to 22. If you print x, would the command display 15 or 22?
- The command would display 22.
Hacks 3 D1
- What is a list?
- A sequence of elements with each element being a variable.
- What is an element
- The items inside of a list.
- What is an easy way to reference the elements in a list or string?
- using print()
- What is an example of a string?
- Phone number
- Create a list with indices
- Index a part of the list that you created.
- Try to index from the end
NamesList = ["Taiyo", "Luna", "Parav", "Ethan", "Nikhil"]
print(NamesList[2])
print(NamesList[4])
The following code is incomplete. Its intended purpose is to increase three numbers, all of which ask for user input, by an amount specified the user. The input code is abstracted, but the actual logic isn’t connected to the abstraction.
num1=input("Input a number. ")
num2=input("Input a number. ")
num3=input("Input a number. ")
add=input("How much would you like to add? ")
# Add code in the space below
numlist = [int(num1), int(num2), int(num3)]
print("User submitted numbers", numlist)
print("Plus " + add)
# The following is the code that adds the inputted addend to the other numbers. It is hidden from the user.
for i in range (len(numlist)):
numlist[i-1] += int(add)
print("Result: ", numlist)
foodlist = ["pizza", "pasta", "sandwich", "burger", "soup"]
print(foodlist)
import getpass, sys
def question_with_response(prompt):
print("Question: " + prompt)
msg = input()
return msg
questions = 3
correct = 0
print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_with_response("Are you ready to take a test?")
rsp = question_with_response("The purpose of lists and dictionaries are to manage the ____ of a program")
if rsp == "complexity":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
rsp = question_with_response("Lists are a form of data ______")
if rsp == "abstraction":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
rsp = question_with_response("Which brackets are used to assign values to a variable to make a list?")
if rsp == "[]":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))
Lessons 3 and 4
Notes:
- An algorithm is a step-by-step process that specifies a series of directives that must be followed in a particular sequence in order to yield the desired outcome.
- An algorithm gives the computer a specific set of instructions, which allows the computer to do everything
- 3 parts of an algorithm: sequencing, selection, and iteration
- A sequence is the way in which something should be done in order to reach a goal, much as how you would follow a teacher's directions.
- An iteration is a loop in which something is repeated until a condition is satisfied, such as when you shut off your computer after finishing your job.
- Arithmetic operator are language that use addition, subtraction, multiplication, division, and modulus operator.
- Modulus operator divides the given numerator by the denominator to find a result,which is finding the remainder for the division(remainder has to an integer).
Hacks 1 D2
Sequencing: 1,2,5 Selection: 3 Iteration: 4
Hacks 2 D2
num1 = 5
num2 = num1 * 3
num3 = num2 / num1 * (9 % 2) * 4
result = (num3 % num1 + num2) % num3 * 3 / 5
print(result)
Lessons 5, 6, and 7
Notes:
- A boolean is a denoting a system of algebraic notation used to represent logical propositions, especially in computing and electronics.
- boolean expressions are either true or false
- Logical operators: not, and, or
- Conditionals allow for the expression of algorithms that utilize selection without a programming language.
- Nested conditional statements consist of conditional statements within conditional statements
Hacks 1 D3
NOT: this operator shows the opposite of what the data shows
AND: evaluates two conditions simuntaneously and checks if both conditions are met
OR: evaluates two conditions simuntaneously but will only make sure if one condition is met
isRunning = False
result = not isRunning
print(result)
winpercentage = .785
if winpercentage > .500 and winpercentage < 1.00:
print("You have a winning record")
wins = 4
losses = 2
if wins > 2 or losses < 4:
print("Your team won the championship!")
x = 23
if x % 2 == 0:
print(x, "is even")
else:
print(x, "is odd")
Level One Challenge
text = "Hi my name is Parav and I am a sophomore at Del Norte HS"
for char in text:
if char == "a" or char == "e" or char == "i" or char == "o" or char == "u" or char == "A":
print(char)
Level Two Challenge
array = []
array.append("Parav")
array.append("Nikhil")
if len(array) == 0:
print("We lost the game")
else:
print(" and ".join(array) + " won the match")
Nested Statements
isRaining = True
temp = 69
if (isRaining):
if temp < 70 :
print("Wear multiple layers.")
else:
print("Wear a single layer")
else:
print("What is the weather like?")
isRaining = True
temp = 50
if (isRaining):
if temp < 70:
print("Wear multiple layers.")
else:
print("Wear a single layer")
else:
if isRaining == False:
print("is it sunny or rainy?")
else:
print("what is the weather like?")
input1 = input("Do you keep up with basketball?")
input2 = input("Do you play fantasy?")
if input1 == "yes":
if input2 == "yes":
print("You should play fantasy basketball with us.")
else:
print("You should talk about basketball with us.")
else :
print("Seems like fantasy basketball isn't a common interest for us.")
Notes:
- Lists are a sequence of variables
- 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
- 9 different methods in list
- Iteration is the repetition of a process or utterance applied to the result or taken from a previous statement.
- Lists, tuples, dictionaries, and sets are iterable objects.
- 2D array is a list of lists, simply
sports = ["football", "hockey", "baseball", "basketball"]
# change the value "soccer" to "hockey"
print (sports)
sports = ["football", "soccer", "baseball", "basketball"]
# add "golf" as the 3rd element in the list
sports.insert(3, "golf")
print (sports)
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 j in range(len(words)):
if inp[i] == words[j][0]:
print(words[j])
keypad = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[" ", 0, " "]]
def print_matrix3(matrix):
for i in range(len(matrix)):
print(*matrix[i])
print_matrix3(keypad)
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("My birthday is", keyboard[3][6] + keyboard[2][0].lower() + keyboard[1][5].lower() , str(keyboard[0][1]) + str(keyboard[0][6]))
Lessons 9 and 11
Notes:
- An algorithm is a process or set of rules to be followed through code.
- When constructing algorithms you want to make sure that your code corresponds with what you want as your output.
- The condition is a boolean expression when an expression outputs either true or false.
- Booleans only output true or false to statements
- The best way to develop an algorithm is to think about all the possible results that can be potentially be outputted.
- Flowcharts help in organizing a way to write your code logically
- Iteration is a process used in algorithms that allows certain things to happen until a condition is satisfied
Homework D5
import random
num1 = random.randint(1, 20)
num2 = random.randint(1, 20)
num3 = random.randint(1, 20)
# generates 3 random numbers, 1-20
highest = max(num1, num2, num3) #finds the maximum number out of the 3 numbers
score = highest #makes the highest number your score
print("3 random generated numbers")
print(num1, num2, num3) # prints out all 3 numbers
print(" ") # creates a space of line, makes it easier to read
print("The highest number(score):")
print(score) #prints out the score (the highest number)
Hacks 2 D5
Link to flowchart can be found linked here
Lessons 12 and 13
Notes:
- A procedure is a named group of programming instructions that may have parameters and return values.
- 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.
- If the procedure just returns a block of statements, you call the procedure by referring to the procedure name, and inputting the arguments.
- There are 2 different types of procedures- ones that return a value and those that simply execute a block of statements
- Picking a descriptive name is important in case you revisit the code later on
- Steps of developing procedure: picking name, thinking of parameters, making a flowchart or writing procedure in pseudocode, and actually developing the procedure.
- A type of procedural abstraction is one 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
- Subdivision of a program into separate subprograms is called modularity
- A procedural abstraction may extract shared features to generalize functionality instead of duplicating code.
- Procedural abstraction is naming and calling a prewritten procedure
Hacks 1 D6
def convertFahrenheit(temp):
celsius = temp - 32
celsius *= 5/9
return celsius
outsideTemp = 69
convertFahrenheit(outsideTemp)
def replaceGrade(currentGrade, newGrade):
if currentGrade < newGrade:
currentGrade = newGrade
return currentGrade
replaceGrade(92, 95)
def grade_needed(current_grade, final_grade_weight, desired_grade):
current_grade /= 100
final_grade_weight /= 100
desired_grade /= 100
return (desired_grade - current_grade * (1 - final_grade_weight)) / final_grade_weight
current_grade = float(input("Enter your current grade as a percentage: "))
final_grade_weight = float(input("Enter the weight of the final exam as a percentage: "))
desired_grade = float(input("Enter your desired overall grade as a percentage: "))
grade_needed = grade_needed(current_grade, final_grade_weight, desired_grade)
print("Your current grade is: " + str(current_grade))
print("The final exam weight is: " + str(final_grade_weight))
print("Your desired grade is: " + str(desired_grade))
print(f"You need to get a grade of {grade_needed * 100}% on the final exam.")
def create_checklist():
checklist = []
while True:
assignment = input("Enter an assignment (or 'done' to finish): ")
if assignment == "done":
break
checklist.append(assignment)
return checklist
checklist = create_checklist()
print("Here is your checklist:")
print(checklist)
Lesson 14 and 15
Notes:
- A library is a collection of precompiled codes that can be used later on in a program for some specific well-defined operations.
- 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.
- Using Libraries makes Python Programming simpler and convenient for the programmer.
- 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 contains specific direction for how the procedures in a library behave and can be used.
- API acts as a gateway for the imported procedures from a library to interact with the rest of your code.
- CollegeBoard uses RANDOM(A, B), to return an integer between integers A and B.
Hacks 1 D7
import random
# Prompt the user to enter the number of random numbers to generate
n = int(input("Enter the number of random numbers to generate: "))
# Prompt the user to enter the minimum and maximum values for the random numbers
a = int(input("Enter the minimum number: "))
b = int(input("Enter the maximum number: "))
# Generate a list of n random numbers in the specified range
numbers = [random.randint(a, b) for _ in range(n)]
# Sort the numbers into even and odd lists
evens = [n for n in numbers if n % 2 == 0]
odds = [n for n in numbers if n % 2 != 0]
# Print the even and odd lists
print(evens)
print(odds)
import numpy as np
# defining the function
def f1(x):
return 2 * x**5 - 6 * x**2 + 24 * x
df1 = np.poly1d(np.polyder(np.poly1d([2, 0, 0, -6, 24, 0])))
print(df1)
import numpy as np
# defining the function
def f2(x):
return (13 * x**4 + 4 * x**2) / 2
df2 = np.poly1d(np.polyder(np.poly1d([13, 0, 4, 0, 0])))
# at x=9
print(df2(9) / 2)
import random
animals = ["dog" for i in range(10)] + ["cat" for i in range(10)]
random_order = []
while len(animals) > 0:
animal = random.choice(animals)
random_order.append(animal)
animals.remove(animal)
print(random_order)
Lesson 16
Notes:
- A simulation is a tested scenario used for viewing results/outputs to prepare for them in real world situations
- 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
Hacks 1 D8
import random
min_temp = -10
max_temp = 30
min_wind = 0
max_wind = 20
min_precip = 0
max_precip = 100
num_days = 10
for day in range(1, num_days+1):
temp = random.uniform(min_temp, max_temp)
wind = random.uniform(min_wind, max_wind)
precip = random.uniform(min_precip, max_precip)
print("Forecast for day {}:".format(day))
print(" Temperature: {:.1f} C".format(temp))
print(" Wind speed: {:.1f} km/h".format(wind))
print(" Precipitation: {:.1f}%".format(precip))
print("")
Hacks 2 D8
Madden NFL is a video game that simulates American football. The game is designed to recreate the experience of playing a real football game, with accurate representations of teams, players, and stadiums, as well as detailed gameplay mechanics that mimic the rules and strategies of the sport. Players can control individual players on the field and make decisions on offense, defense, and special teams, with the goal of outscoring their opponent and winning the game. The game uses advanced algorithms and artificial intelligence to generate realistic outcomes and challenges for players, providing an immersive and engaging simulation of the sport of American football.
Lesson 17 and 18
Notes:
- Algorithm efficiency is the ability of an algorithm to solve a problem in an efficient way
- A decision problem is a problem in computer science and mathematics that can be solved by a yes-no answer, also known as a binary answer
- There are two types of decision problems that Collegeboard goes over: Decidable Problems Undecidable Problems
- A decidable problem is an algorithm that can always have an output of yes or no given any input. It is always correct.
- The code keeps adding 1 to the variable number until number is no longer an integer(This is not the python data type "integer", it's the integer in number theory).
- It states that it is not always possible to correctly determine whether a code halts or runs forever.
- Note that while a computer may take a long time to run a section of code, it does not mean that the computer is going to run forever.
- Humans are able to solve some undecidable problems. The entire Halting Problem example was to prove that computers cannot solve undecidable problems.
Hacks 1 D9
One situation in which a computer might run into an undecidable problem is when it is asked to determine whether a given program will halt or run indefinitely. This problem, known as the Halting Problem, is considered undecidable because there is no algorithm that can consistently determine whether a given program will halt or run indefinitely for all possible inputs.The Halting Problem is a classic example of an undecidable problem because it demonstrates the inherent limitations of computation. In order to determine whether a program will halt, a computer would need to be able to analyze the program and its input, and then make a prediction about its future behavior. However, because programs can be arbitrarily complex and can exhibit unpredictable behavior, it is impossible for a computer to accurately predict whether a given program will halt or run indefinitely. To illustrate this point, consider a program that takes an input and then checks whether that input is a valid proof of the Halting Problem itself. If the input is a valid proof, then the program will halt; if the input is not a valid proof, then the program will run indefinitely. Because there is no way to determine whether a given input is a valid proof of the Halting Problem, it is impossible for a computer to accurately predict whether this program will halt or run indefinitely for all possible inputs.
Hacks 2 D9
Algorithm 2 significantly outperformed the first algorithm. While the first algorithm took longer to complete and the time increased as the value of x increased, the time taken by algorithm 2 was always less than 10 and did not depend on the value of x.
Hacks 3 D9
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
x = 270
y = 192
result = gcd(x, y)
print(result)
i = 0
while True:
print(i)
i += 1