Hacks
- Lesson 1-2 Hacks
- Lesson 3 & 4 Hacks
- Lesson 5-6 Hacks
- Lesson 9 and 11 Hacks
- Lesson 12-13 hacks
- Lesson 16 Hacks
- Lesson 17-18
Observations: - In a program, a variable is an abstraction that retains a value. Each variable is paired with data storage that can only hold one 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 thought of as "containers," and each one has a name that describes what it is meant to hold.
- Depending on what is being represented, variables have a variety of data types that hold particular types of data.
Hacks 1
Questions (College Board's Essential Knowledge):
- What exactly IS a variable?
- A variable is an abstraction that stores a value inside of a program, and each variable has a corresponding data storage that holds just one value at a time
- What is the best data type to represent someone's dog's name?
- The best data type is a string
- Why is it important to give variables specific names before containing values?
- In order for them to have a name that is appropriate for the value that will be contained.
- What is the best way to represent someone's phone number?
- The best way to ensure that the numbers don't obstruct the code is to use a string.
Bonus (Not required but important to know):
- How can we update a variable's value
- To update a variable's value u can do it using + or - for incrementing or decrementing
- What function is used to receive a user's input?
- input()
Hacks 2
Answer these:
- In your own words, briefly explain by writing down what an assignment operator is
- The equal sign (=) serves as the assignment operator and enables the assignment of code elements to values.
- 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?
- It would display 22.
Hacks 3
- What is a list?
- a series of elements, each of which is a variable.
- What is an element
- An element are 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?
- Hello World
- Create a list with indices
- Index a part of the list that you created.
- Try to index from the end
NamesList = ["Nikhil", "Taiyo", "Lunda", "Parav", "Ethan"]
print(NamesList[2])
print(NamesList[4])
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 = ["eggs", "bread", "chicken", "rice", "pizza"]
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))
Notes: An algorithm is a sequential process that describes a set of instructions that must be followed in a specific order in order to produce the intended result. An algorithm provides the computer with a set of instructions that it can follow to complete any task. There are three components to an algorithm: sequencing, selection, and iteration. Similar to how you would follow a teacher's instructions, a sequence is the order in which something should be done in order to accomplish a goal. A loop, or iteration, occurs when something is repeated until a condition is met, such when you turn off your computer after finishing a task. Languages that utilize arithmetic operators include those that use addition, subtraction, multiplication, division, and modulus.
Hacks 1
Sequencing: 1,2,5 Selection: 3 Iteration: 4
Hacks 2
num1 = 5
num2 = num1 * 3
num3 = num2 / num1 * (9 % 2) * 4
result = (num3 % num1 + num2) % num3 * 3 / 5
print(result)
Lesson 5-6 Hacks
Explain in your own words what each logical operator does.
- Not: This displays the opposite of the data inputed.
- And: This helps determine if the conditions are met
- Or: This may help determine if one of the conditions is met.
Code your own scenario that makes sense for each logical operator
walking = True
result = not(walking)
print(result)
USD = 10
Coins = 100
if USD >= 9 and Coins >= 100:
print("You have a lot of money")
else:
print("you have less money")
Cars = 100
Ferrari = 2
if Ferrari >= 1 or Cars >= 101:
print("you have good cars")
1 point for defining all the key terms in your own words. 0.5 points if you use examples that show you truly understand it.
- Selection: This is a piece of code that is determined if the ouput is true or false.
- Algorithm: An algorithm is a process and a set of rules that should be followed when doing calculations.
- Conditional statements: These are a set of rules to see if a condition is met.
1 point for writing a program that uses binary conditional logic. 0.5 points if it is original and shows complexity
x = int(input("choose a number"))
if x % 2 == 0:
print(x, "is even")
else:
print(x, "is odd")
Lesson 9 and 11 Hacks
Notes
First, create algorithms.
Outlining an algorithm's procedure before coding is a smart idea. This guarantees that it is correctly sequenced. You should use a flowchart or simple language to represent the algorithm. You can use visualization to more clearly observe how the entire algorithm works. This might make the coding process more productive and efficient.
2) Evaluation of Iteration and Selection
Iterative algorithms repeat a function until a target is reached. We can use iteration to more simply represent an algorithm without illustrating all the repeated steps. Algorithms with selection only execute specific functions in the case of certain conditions being true or false.
3) Why are algorithms used?
It is simple to think that two algorithms that look quite similar do the same task. That is not the case, though, because we have learned to detect minute variations in code and essentially debug.
isCold = True
isHot = False
if isCold == True:
print(" Jacket necessary!")
elif isHot == True:
print("No Jacket necessary!")
isCold = False
isHot = True
puddles = not(isCold) and isHot
if isHot == False:
print("No Jacket!")
elif isCold == True:
print("Jacket!")
1) When the code first runs, there are 5 coins available.
2) The AmountMoney variable is set to True.
3) $1 is subtracted from the coins variable but AmountMoney stays true.
4) The string "Broke!" is printed when the variable coins reaches a value of 0. At that point, AmountMoney is set to False.
5) End!
Coins = 10
AmountMoney = True
while(AmountMoney == True):
Coins -= 1
if Coins == 0:
AmountMoney == False
print("Broke")
break
import random
num_guesses = 0
user_guess = -1
upper_bound = 100
lower_bound = 0
number = random.randint(0,100)
print(f"I'm thinking of a number between 0 and 100.")
def guess():
num = input("Input your guess")
return num
def search(number, guess):
global lower_bound, upper_bound
if int(guess) < int(number):
print("Too low, try again!!!!")
lower_bound = guess
return lower_bound, upper_bound
elif int(guess) > int(number):
print("Too high, try again!!!!! ")
upper_bound = guess
return lower_bound, upper_bound
else:
upper_bound, lower_bound = guess, guess
return lower_bound, upper_bound
while user_guess != number:
user_guess = guess()
num_guesses += 1
print(f"You guessed {user_guess}.")
lower_bound, upper_bound = search(number, user_guess)
if int(upper_bound) == int(number):
break
else:
print(f"Guess a number between {lower_bound} and {upper_bound}.")
print(f"You guessed the number in {num_guesses} guesses!")
Answer is in image below
Answer: Set 1: 80, Set 2: 74, Set 3: 96
Answer is C
numListOne = [12,14,44,57,79,80,99]
numListTwo = [92,43,74,66,30,12,1]
numListThree = [7,13,96,111,33,84,60]
numLists = [numListOne, numListTwo, numListThree]
for x in range(len(numLists)):
numLists[x].sort()
middle = int(len(numLists[x])/2)
print("Middle Index of List #",x+1,"is",numLists[x][middle])
a) Procedure: A block of code that is created to perform a given task - essentially a function.
b) Parameter: A variable that is utilized in a function that enables data to be imported into said function.
a) A return value is a value that a function or method returns to the caller code once it has completed executing. Once the function or method has completed its task, the value is returned to the caller code.
b) Output parameters, which are variables supplied by reference to a function or method and used to return a value to the caller code, are another type of parameter. They are frequently used to have a single function or method return a number of values.
import math
userNum = float(input())
def sqrt(userNum):
return userNum
sqrt = math.sqrt(userNum)
print("Square root of", userNum , ":", float(sqrt))
x = 20
y = 100
# Set function
def addition(x,y):
sum = x + y
return(sum)
#Print the result
print(addition(x,y))
def split_string(s):
# use the split() method to split the string into a list of words
words = s.split(" ")
# initialize a new list to hold all non-empty strings
new_words = []
for word in words:
if word != "":
# add all non-empty substrings of `words` to `new_words`
new_words.append(word)
return words
# this function takes a list of words as input and returns the number of words
# that start with the given letter (case-insensitive)
def count_words_starting_with_letter(words, letter):
count = 0
# loop through the list of words and check if each word starts with the given letter
for word in words:
# use the lower() method to make the comparison case-insensitive
if word.lower().startswith(letter):
count += 1
return count
# this function takes a string as input and returns the number of words that start with 'a'
def count_words_starting_with_a_in_string(s):
# use the split_string() function to split the input string into a list of words
words = split_string(s)
# use the count_words_starting_with_letter() function to count the number of words
# that start with 'a' in the list of words
count = count_words_starting_with_letter(words, "a")
return count
# see above
def count_words_starting_with_d_in_string(s):
words = split_string(s)
count = count_words_starting_with_letter(words, "d")
return count
# example usage:
s = " This is a test string! Don't you think this is cool? "
a_count = count_words_starting_with_a_in_string(s)
d_count = count_words_starting_with_d_in_string(s)
print("Words starting with a:", a_count)
print("Words starting with d:", d_count)
x = 1 y = 2
<button id= “add” type=“button” onclick=“addition(x,y)“>addition</button>
<p id = “output”>
</p><button id= “subtract” type=“button” onclick=“subtraction(x,y)“>subtraction</button>
<p id = “output2”>
</p><button id= “divide” type=“button” onclick=“divide(x,y)“>divide</button>
<p id = “output3”>
</p><button id= “multiply” type=“button” onclick=“multiply(x,y)“>multiply</button>
<p id = “output4”>
</p>Enter First Number:
Enter Second Number:
Hacks 1
What makes it a simulation?
- Instead of having to endure the discomfort of visiting stores and trying on clothing to determine whether it fits, individuals can just click online, enter their measurements, and the simulation will determine whether you will fit the item of clothing.
What are its advantages?
- One advantage is that it is fast and has random results
Because you cannot presume that real coins are impartial like those in the simulation, an experiment would be preferable.
questions_number = 6
answers_correct = 0
questions = [
"True or False: Simulations will always have the same result. \n A: True, \n B: False",
"True or False: A simulation has results that are more accurate than an experiment \n A: True, \n B: False",
"True or False: A simulation can model real world events that are not practical for experiments \n A: True, \n B: False",
"Which one of these is FALSE regarding simulations \n A: Reduces Costs, \n B: Is safer than real life experiments, \n C: More Efficient, \n D: More accurate than real life experiments",
"Which of the following scenarios would be the LEAST beneficial to have as a simulation \n A: A retail company wants to identify the item which sold the most on their website, \n B: A restaurant wants to determine if the use of robots will increase efficiency, \n C: An insurance company wants to study the impact of rain on car accidents, \n D: A sports car company wants to study design changes to their new bike design ",
"Which of the following is better to do as a simulation than as a calculation \n A: Keeping score at a basketball game, \n B: Keeping track of how many games a person has won, \n C: Determining the average grade for a group of tests, \n D: Studying the impact of carbon emissions on the environment"
]
question_answers = [
"B",
"B",
"A",
"D",
"A",
"D"
]
print("Welcome to the Simulations Quiz!")
def ask_question (question, answer):
print("\n", question)
user_answer = input(question)
print("You said: ", user_answer)
if user_answer == answer:
print("Correct!")
global answers_correct
answers_correct = answers_correct + 1
else:
print("You are incorrect")
for num in range(questions_number):
ask_question(questions[num], question_answers[num])
print("You scored: ", answers_correct, "/6")
def parse_input(input_string):
if input_string.strip() in {"1", "2", "3","4", "5", "6"}:
return int(input_string)
else:
print("Please enter a number from 1 to 6.")
raise SystemExit(1)
import random
def roll_dice(num_dice):
roll_results = []
for _ in range(num_dice):
roll = random.randint(1, 14)
roll_results.append(roll)
return roll_results
num_dice_input = input("How many dice do you want to roll? [1-6] ")
num_dice = parse_input(num_dice_input)
roll_results = roll_dice(num_dice)
print("you rolled:", roll_results)
import random
total_heads = 0
total_tails = 0
count = 0
while count < 100:
coin = random.randint(1, 2)
if coin == 1:
print("Heads!\n")
total_heads += 1
count += 1
elif coin == 2:
print("Tails!\n")
total_tails += 1
count += 1
print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")
Collatz One of the most well-known unsolved mathematical puzzles is the Collatz conjecture. The conjecture asks if every positive integer will eventually become 1 if two basic arithmetic processes are repeated.
Hailstone digits Hailstone Numbers are the series of integers produced by the Collatz conjecture. Examples: N = 7 as an input Output: Hailstone 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 5, 16, 8, 4, and 1 are the numbers. ### Iteration The act or process of iterating or repeating: for example, a process where the repetition of a series of actions produces outcomes that get progressively closer to the desired outcome.
Unsolvable issues An undecidable problem is one that should have a "yes" or "no" response, but for which there is no method that can provide an accurate response for all inputs.
Intractable issues A issue is considered intractable if there is no known algorithm that can be created to solve it.
Extra research:
The Collatz Conjecture, also known as the 3x + 1 problem or the Syracuse Problem, is an unsolved problem in mathematics. It is a conjecture that states that for any positive integer, if you apply a certain process, you will eventually reach the number 1. The process involves taking any positive integer and, if it is even, dividing it by 2, and if it is odd, multiplying it by 3 and then adding 1. This process is then repeated on the resulting number, and the process is repeated until the number 1 is reached.
This conjecture has been studied extensively and has been proven to be true for all numbers up to 5 × 1018. However, the conjecture has not been proven for all numbers, and it is possible that it is false. This conjecture has been studied since the 1930s and is one of the most famous unsolved problems in mathematics.
i = int(input("Please input a number: "))
list = []
def collatz_seq(n):
list = []
while n != 1:
if (n % 2):
n = 3*n + 1
else:
n = n/2
list.append(n)
return list
result = collatz_seq(i)
print("Input:" , i)
print(result)
print("Iteration count:", len(result))
car = []
car.append({
"Make": "BMW",
"Model": "M4 CSL",
"Year": "2023",
})
def loop():
for data in car:
print(data)
loop()
car = "Make: BMW", "Model: M4 CSL", "Year: 2023"
print(car)
Efficiency is properly demonstrated by Algorithm 1, which appends the list and makes use of a for loop to present the data for the specified car in a logical sequence. Because the data is only displayed in the input order, Algorithm 2 is inefficient. Algorithm efficiency in computer science is the measure of how well a particular algorithm performs when compared to other algorithms. It is typically calculated by measuring the amount of time and space it takes to complete a task.
import datetime
#Creating a dictionary that stores tasks and their respective times
daily_tasks = {
"Wake Up" : "6:00 am",
"Breakfast" : "7:00 am",
"Go to Work" : "8:00 am",
"Lunch" : "12:00 pm",
"Work" : "1:00 pm",
"Gym" : "4:00 pm",
"Dinner" : "7:00 pm",
"Sleep" : "10:00 pm"
}
#Getting the current time
current_time = datetime.datetime.now()
#Printing the current time
print("Current Time:", current_time.strftime("%H:%M %p"))
#Looping through the dictionary
for task, time in daily_tasks.items():
#Getting the time in datetime object
task_time = datetime.datetime.strptime(time, "%H:%M %p")
#Checking if the task has been completed
if task_time < current_time:
print("Task", task, "has been completed")
else:
print("Task", task, "is yet to be completed")