Pre-Tree Hacks
The hacks for each lesson
- 3.1 and 3.2 Hacks
- 3.3 and 3.4 Hacks
- 3.8 & 3.10 Hacks
- 3.9 - 3.11 Hacks
- 3.12 & 3.13 Hacks
- 3.14 - 3.15
- 3.17 - 3.18
name = "Paaras"
age = 15
is_apcsp_student = True
print("Hello, my name is " + name + ". I am " + str(age) + " and it is " + str(is_apcsp_student) + ", I am in computer science.")
Below is the code completing the hacks for Noor's section:
# variable name and value, and is used to set a variable to something.
name = "Paaras"
print(name)
# In the pseudocode used by CollegeBoard, the assignment operator is "<-" between the
# variable name and value.
# It depends where the print function is called. For this case, we will assume that the
# print function is called finally. In this case, the command will display the number 22
x = 15
x = 22
print(x)
Below is the fixed code for the calendar. Put this code in a runnable HTML document and press CTRL+O in a new tab, it should run the code the correct way, showing my understanding of variables (the binary converter never showed up for me).
<div class="container">
<div class="calendar">
<div class="month">
<button id="prev" onclick="prev()">Prev</button>
<button id="next" onclick="next()">Next</button>
<p id="month">Month Here</p>
</div>
</div>
</div>
<script>
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let index = 0;
function next() {
if (index > 11) {
index = 0;
}
else {
index += 1;
}
document.getElementById("month").innerHTML = months[index]
}
function prev() {
if (index < 0) {
index = 11;
}
else {
index -= 1;
}
document.getElementById("month").innerHTML = months[index]
}
document.getElementById("month").innerHTML = months[index]
</script>
# of the same data type (in Python, at least).
# An element of a list is a single item. Below is an example of a list, with three
# elements:
list = [64, "Hello World", True]
# A programmer can access a list element from either side of a list. If the programmer is
# accessing the element from the end, the programmer uses negative numbers, and positive
# numbers for the beginning.
# Prints "True"
print(list[-1])
# Prints "Hello World"
print(list[1])
# Strings are just arrays of characters, meaning that list functions can be used on
# strings as well.
string = "Hello World"
# Prints "o"
print(string[4])
# The Actual Hacks:
foods = ["chicken", "burrito", "taco", "ramen", "fruits", "vegetables"]
print("One of my favorite foods is " + foods[2] + ". Another favorite food of mine is " + foods[-2])
Below is the code completing the hacks for Steven's section:
num1 = input("Input a number >> ")
num2 = input("Input another number >> ")
num3 = input("Input one last number >> ")
nums = []
nums.append(int(num1))
nums.append(int(num2))
nums.append(int(num3))
print("Original list: " + str(nums))
for i in range(0, len(nums)):
nums[i-1] += 1
print("Modified list: " + str(nums))
Below is the code completing the hacks for Liav's section:
import getpass, sys
def question_with_response(prompt):
print("Question: " + prompt)
msg = input()
return msg
questions = 4
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))
foods = ["pizza", "hot dog", "sushi", "strawberry", "sandwich"]
print(foods)
- Why are using lists better for a program, rather than writing out each line of code? I'm glad you asked. This gives me an opportunity to bring up a point that is important about data abstraction. When programmers say that lists make code easier, others think that lists are the key to have a relaxing time programming. This is a completely wrong thing to think, because programs, regardless of lists, can still be hard to code. Abstraction, despite the misconceptions, don't make code easier, but rather, they make code less prone to errors, which is commonly referred to as making it "simpler." Something I've found while doing the hacks for this lesson.
- Make your own list the “long and slow way” then manage the complexity of the list
food1 = "pizza"
food2 = "hot dog"
food3 = "sushi"
food4 = "strawberry"
food5 = "sandwich"
foods = [food1, food2, food3, food4, food5]
print(foods)
Below is the code completing the hacks for Luka's section
Luka's Hacks:
- Set item to number to search for.
- Get next number in the list.
- If number = item, display "item found."
- If there are more numbers in the list, go back to Step 2.
- Display "item not found."
Steps 2 and 4 are iteration. Steps 3 and 4 are selection. Steps 1-5 are a sequence
nums = [1, 2, 3, 4, 5, 6, 7]
num_to_find = 5
for i in nums:
if nums[i] == num_to_find:
print("item found at index " + str(i))
break
Below is the code completing the hacks for Antony's section:
num1 = 5
num2 = num1 * 3 # 5 / 3 = 15
num3 = num2 / num1 * (9 % 2) * 4 # 9 % 2 = 1, 1 * 5 = 5, 15 / 5 = 3
result = (num3 % num1 + num2) % num3 * 3 / 5 # Essentially, equals 3
print(result)
# For the crossword:
# 1. Iteration
# 2. Sequence
# 3. Algorithm
Hello! You will be asked 3 questions. ready, set, go!
--- Options for question #1 --- A. The amount of bytes that the string takes up. B. The length of the string. C. The String but in binary. D. The Unicode of each letter in the string.
--- !!! CAPITAL LETTERS ONLY !!! ---
--- Question #1 --- What does the command 'len' ouput about the string? B B is correct!
--- Options for question #2 --- T. True! F. False :(
--- Question #2 --- The command 'substring' is used to conjoin two strings F F is correct!
--- Options for question #3 --- A. Syntax Error B. 'Hel WorldHe' C. 'Helikopter Helikopter' D. 'lo Wo'
--- Question #3 --- What will print('Hello World'[3:8]) print? (pretend that the single quotation marks are regular quotation marks.) D D is correct!
--- score --- runner you scored 3/3 --- !!! SCREENSHOT THIS AND INSERT IT ON YOUR BLOG !!! ---
Below is the code completing the hacks for Taiyo's section:
# while loop.
# Hacks II and III: Below is an algorithm that solves one of the hacks from my (3.6) lesson,
# that uses iteration (finds the element in the list that appears an odd number of times):
def find_it(seq):
result = 0
for i in seq:
if seq.count(i) % 2 != 0:
result = i
return result
nums = [0, 1, 0, 1, 2, 3, 4, 3, 5, 4, 5]
print(find_it(nums)) # Should output 2
Below is the code completing the hacks for Parav's section:
# Hack II:
i = 11
for i in range(0, i):
if i < 0:
break
else:
print(i)
i -= 1
##########################################################################################
print()
##########################################################################################
# Hack III:
other_nums = [3,16,29,42,55,68,81]
index = 0
while index <= len(other_nums) - 1:
print(other_nums[index])
index += 1
Below is the code completing the hacks for Luna's section:
nums = [10, 15, 20, 25, 30, 35]
min = 10
result = 0
for i in range(0, len(nums)):
if int(nums[i]) <= min:
result = nums[i]
else:
continue
print(result)
Below is the code completing the hacks for Ethan's section:
import getpass, sys
import random
def ask_question (question, answer):
print(question)
ans = input(question)
print(ans)
if ans == answer:
print("Correct!")
return 1
else:
print("Wrong")
return 0
question_list = ["What allows a value to be inserted into a list at index i?" , "What allows an element at index i to be deleted from a list?" , "What returns the number of elements currently in a specific list?" , "What allows a value to be added at the end of a list?"]
answer_list = ["index()", "remove()", "length()" , "append()"]
# Set points to 0 at the start of the quiz
points = 0
# If the length of the quiz is greater than 0, then random questions will be chosen from the "question_list" set
while len(question_list) > 0:
index = random.randint(0, len(question_list) - 1)
# The points system where a point is rewarded for each correct answer
points = points + ask_question(question_list[index], answer_list[index])
# If a question or answer has already been used, then it shall be deleted
del question_list[index]
del answer_list[index]
# Calculating score using the points system and dividing it by the total number of questions (6)
score = (points / 4)
# Calculating the percentage of correct answers by multiplying the score by 100
percent = (score * 100)
# Printing the percentage, and formatting the percentage in a way where two decimals can be shown (through "{:.2f}")
print("{:.2f}".format(percent) + "%")
# Adding final remarks based upon the users given scores
if points >= 5:
print("Your total score is: ", points, "out of 4. Amazing job!")
elif points == 4:
print("Your total score is: ", points, "out of 4. Not too bad, keep on studying! " )
else:
print("Your total score is: ", points, "out of 4. Its alright, better luck next time!")
Below is the code completing the hacks for Claire's section
# in the lesson. Some comparisons in algorithms that may look the same are not, and
# depending on the output, can return different results. Similarly, algorithms that look
# different can return the same results. In the context of this lesson, boolean and
# conditionals can be used to return the same results.
#
# Below is a code snippet converting
# booleans to conditionals:
score = input("What's your score?")
isGreaterThanFifty = int(score) > 50
isLessThanFifty = int(score) < 50
if isGreaterThanFifty:
print("Your score is greater than 50")
elif isLessThanFifty:
print("Your score is less than 50")
else:
print("Your score is 50")
Below is the code completing the hacks for Annika's section:
# item. It must return the display text as shown in the examples:
# [] --> "no one likes this"
# ["Peter"] --> "Peter likes this"
# ["Jacob", "Alex"] --> "Jacob and Alex like this"
# ["Max", "John", "Mark"] --> "Max, John and Mark like this"
# ["Alex", "Jacob", "Mark", "Max"] --> "Alex, Jacob and 2 others like this"
def likes(names):
if len(names) == 0:
return "no one likes this"
if len(names) == 1:
return str(names[0]) + " likes this"
if len(names) == 2:
return str(names[0]) + " and " + str(names[1]) + " like this"
if len(names) == 3:
return str(names[0]) + ", " + str(names[1]) + " and " + str(names[2]) + " like this"
if len(names) >= 4:
return str(names[0]) + ", " + str(names[1]) + " and " + str(len(names) - 2) + " others like this"
names = ["Peter"]
likes(names)
newNames = ["Alex", "Jacob", "Mark", "Max"]
likes(newNames)
Below is the code completing the hacks for Grace's section:
import random
#sets variables for the game
num_guesses = 0
user_guess = 0
upper_bound = 100
lower_bound = 0
#generates a random number
number = random.randint(1,100)
# print(number) #for testing purposes
print(f"I'm thinking of a number between 1 and 100.")
#Write a function that gets a guess from the user using input()
def guess():
guessInput = input("Guess the number >>")
if input == None or input == "":
guess()
else:
return int(guessInput)
#Change the print statements to give feedback on whether the player guessed too high or too low
def search(number, guess):
global lower_bound, upper_bound
if guess < number:
print("Guess higher") #change this
lower_bound = guess
elif guess > number:
print("Guess lower") #change this
upper_bound = 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)
print(f"Guess a number between {lower_bound} and {upper_bound}.")
print(f"You guessed the number in {num_guesses} guesses!")
Below is the code completing the hacks for Claire's section:
# the middle index, making it the one that would be looked at.
# 3. C
Below is the code completing the hacks for Kaiden and Amay's section:
questionNum = 3
correct = 0
questions = [
"What is are correct names for a procedure? \n A) Method \n B) Function \n C) Both",
"What is a procedure? \n A) Sequencing \n B) Selection \n C) Iteration \n D) All",
"Use this for following question: \n def inchesToFeet(lengthInches): \n\t lengthFeet = lengthInches / 12 \n\t return lengthFeet \n\n What is the procedure name, the parameter, and what the procedure returns? \n A) feetToInches, lengthInches, lengthMeters \n B) inchesToFeet, lengthInches, lengthFeet \n C) inchesToFeet, lengthFeet, lengthInches \n D) lengthInches, inchesToFeet, lengthFeet"]
answers = ["c", "d", "b"]
def qna(question, answer):
print("Question:", question)
response = input()
print("Answer:", response)
if response.lower() == answer:
print("Correct :) \n")
global correct
correct += 1
else:
print("Incorrect :( \n")
for x in range(questionNum):
qna(questions[x], answers[x])
print("Score:", correct, "/ 3")
#
# 2. The quiz work and score are above.
#
# 3. Return values are basically the output of a procedure. When the parameters are
# inputted into the function being called, the return value is what is given. An output
# parameter is something that is required to be defined when calling a procedure.
#
# Below is a code snippet that finds the square root of any integer:
def square_root(number):
return number ** 0.5
num = input("Enter a number")
print(square_root(int(num)))
Below is the code completing the hacks for Safin's section:
# programming much easier, but it reduces the amount of errors that can occur due to
# repetition of code due to absence of abstraction. Procedural abstraction through exactly
# that, procedures, is a great way to use abstraction on algorithms to manage code
# complexity.
# 2. Below is a procedure that ultimately uses multiple abstraction:
def add_numbers(a, b):
return a + b
def sum_is_even(a, b):
x = add_numbers(a, b)
if x % 2 == 0:
return "Number is even"
else:
return "Number is odd"
num1 = input("Enter one number")
num2 = input("Enter another number")
print(sum_is_even(num1, num2))
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
def count_anything(sentence, letter):
words = split_string(sentence)
count = count_words_starting_with_letter(words, letter)
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)
letter = input("Enter a letter")
output = count_anything(s, str(letter))
print("Words starting with " + str(letter) + ": " + str(output))
Below is the code completing the hacks for David and Alex's section:
#
# Procedure names: The name used to identify a unique procedure in a program
# Arguments: Parameters in a procedure that are used as "input" to return an output based on
# said input.
# 2. It is not in JavaScript/HTML, it is in Python, but it is interactive.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
print("Enter a number")
num1 = int(input("Enter a number"))
print(num1)
print("Enter another number")
num2 = int(input("Enter another number"))
print(num2)
print("Do you want to add, subtract, multiply, or divide?")
action = str(input("Do you want to add, subtract, multiply, or divide?"))
print(action)
if action == "add":
print(add(num1, num2))
elif action == "subtract":
print(subtract(num1, num2))
elif action == "multiply":
print(multiply(num1, num2))
elif action == "divide":
print(divide(num1, num2))
# A library, or module, is any collection of functions, variables, and other code that can
# be
# used to help perform tasks and solve problems. There are many modules installed with
# Python
# today, such as turtle, random, math, pandas, and so much more. One can use the "import"
# keyword to bring in a module to start using, and once one does that, can use all the
# functions and code from the module possible. This is a really efficient way of taking code
# from other sources to save time and not re-coding already coded features.
Below is the code completing the hacks for Ethan's section:
import random
dice = 0
print("You're wondering if you should or shouldn't do something. Ask.")
question = input("You're wondering if you should or shouldn't do something. Ask.")
print(question)
dice = random.randint(1, 15)
if dice < 6:
print("Don't do it.")
elif dice > 5 and dice < 11:
print("Eh... I don't know, try again")
else:
print("You should do it.")
# The import keyword, in this case, *import random*, is used to bring in all the functions,
# variables, and the overall module of random into the program. One can choose to import
# only certain functions and certain variables from the random module.
#
# But random is not the only library we can import. We can import turtle for animation,
# pandas for AI, math for mathematics, matplotlib.py for graphing, and many more.
import random
spinner = random.randint(1, 8)
# Values 1 - 3 are green
# Valeus 4 and 5 are blue
# 6 is purple, 7 is red, and 8 is orange
if (spinner > 4):
print("Green")
if (spinner == 4 or spinner == 5):
print("Blue")
if (spinner == 6):
print("Purple")
if (spinner == 7):
print("Red")
if (spinner == 8):
print("Orange")
extra_credit_var = random.randint(12, 20) # numbers 12-20 can be chosen, including 12 and 20
Below is the code completing the hacks for Alexa, Lydia, and Ava's section:
# Notes:
# This automates the roles of actual players, where random_num is the person who thinks of
# a number, and the user is the player who guesses it.
# Its advantages is that, unless modifications to cheat are made to this program, it is
# completely fair. However, it does not have the same level of fun that games would have
# with a two players who can emotionally respond to one another. Overall, this is a good
# simulation for a test environment.
# Depending on the goals of this simulation, an experiment may or may not be better. If the
# goal of this project is to study the psychological factors of this game, then a live
# experiment might be better. If the goal is to observe the working concepts of the game,
# a simple simulation like this one will do fine:
random_num = random.randint(1, 10)
print("Guess the number I'm thinking of, between 1 and 10")
guess = int(input("Guess the number I'm thinking of, between 1 and 10"))
print("You guessed " + str(guess))
if guess == random_num:
print("Correct")
else:
print("Wrong, the number was " + str(random_num))
Below is the code completing the hacks for Sri, Lydia, and Ava's section.
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")
# Dice can be used for many things. One can guess the number that the dice is rolled on. One
# can make a boolean statement depending on if the dice is greater than a certain number.
# The possibilities are quite endless. Below is a decision game that uses "dice" to help
# the user make decision (to put these notes into practice):
import random
dice = 0
print("You're wondering if you should or shouldn't do something. Ask.")
question = input("You're wondering if you should or shouldn't do something. Ask.")
print(question)
dice = random.randint(1, 15)
if dice < 6:
print("Don't do it.")
elif dice > 5 and dice < 11:
print("Eh... I don't know, try again")
else:
print("You should do it.")
For the extra credit, I did code Guess the Number at the very top of 3.16 hacks.
Below is the code completing the hacks for Quinn's section:
# - Collatz conjecture: "Whether or not repeating two simple arithmetic operations will
# eventually transform every positive integer into 1."
# - Hailstone numbers: "The sequence of integers generated by Collatz conjecture are called
# Hailstone Numbers. Examples:Input : N = 7 Output : Hailstone Numbers: 7, 22, 11, 34, 17, 52,
# 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 No.> ### Iteration The action or a process of
# iterating or repeating:such as. : a procedure in which repetition of a sequence of
# operations yields results successively closer to a desired result."
# What is Algorithm Efficiency?
# Algorithmic efficiency is an aspect of algorithmic programming that measures the
# number of steps needed to solve a problem. For instance, If I wanted to create a sorting
# algorithm that sorts numbers the numbers [2,4,5,1,3]from least to greatest, rather than
# having an algorithm that compares itself to the next number and swaps accordingly it would
# be more efficient if you had a program that scans through all the numbers and checks whether
# a number is smaller or bigger than the rest than and sorts accordingly. Both of the
# algorithms had the same objective, but one runs more efficiently than the other.
def collatz(num):
if num % 2 != 0:
num = num * 3
num = num + 1
return num
elif num % 2 == 0:
num = num / 2
return num
num = 7
for i in range(16):
num = collatz(num)
print(num)
Below is the code completing the hacks for Kush and Yasha's section
def inefficientPrinting():
print(1)
print(2)
print(3)
print(4)
print(5)
# Efficient code that takes up less space and is easier to code
def efficientPrinting():
for i in range(1, 6):
print(i)
print("Inefficient code:")
inefficientPrinting()
print("Efficient code: ")
efficientPrinting()