Lesson 1-2 Hacks

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):

  1. 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
  1. What is the best data type to represent someone's dog's name?
    • The best data type is a string
  2. 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.
  3. 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):

  1. How can we update a variable's value
    • To update a variable's value u can do it using + or - for incrementing or decrementing
  2. What function is used to receive a user's input?
    • input()

Hacks 2

Answer these:

  1. 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.
  2. In Collegeboard pseudocode, what symbol is used to assign values to variables?
    • <--
  3. 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

  1. What is a list?
    • a series of elements, each of which is a variable.
  2. What is an element
    • An element are the items inside of a list.
  3. What is an easy way to reference the elements in a list or string?
    • using print()
  4. 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])
Lunda
Ethan
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)
User submitted numbers [1, 2, 3]
Plus 4
Result:  [5, 6, 7]
foodlist = ["eggs", "bread", "chicken", "rice", "pizza"]
print(foodlist)
['eggs', 'bread', 'chicken', 'rice', 'pizza']
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))
Hello, nikhilchakravarthula running /Users/nikhilchakravarthula/opt/anaconda3/bin/python
You will be asked 3 questions.
Question: Are you ready to take a test?
Question: The purpose of lists and dictionaries are to manage the ____ of a program
complexity is correct!
Question: Lists are a form of data ______
abstraction is correct!
Question: Which brackets are used to assign values to a variable to make a list?
[] is correct!
nikhilchakravarthula you scored 3/3

Lesson 3 & 4 Hacks

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)
3.0

Crossword Puzzle

Down: 1) iteration 2) selection

Across: 3) sequence

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)
False
USD = 10
Coins = 100
if USD >= 9 and Coins >= 100:
    print("You have a lot of money")
else:
    print("you have less money")
You have a lot of money
Cars = 100
Ferrari = 2
if Ferrari >= 1 or Cars >= 101:
    print("you have good cars")
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")
12 is even

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!")
 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
    
Broke
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!")
I'm thinking of a number between 0 and 100.
You guessed 30.
Too low, try again!!!!
Guess a number between 30 and 100.
You guessed 72.
Too low, try again!!!!
Guess a number between 72 and 100.
You guessed 91.
Too high, try again!!!!! 
Guess a number between 72 and 91.
You guessed 83.
Too high, try again!!!!! 
Guess a number between 72 and 83.
You guessed 75.
Too high, try again!!!!! 
Guess a number between 72 and 75.
You guessed 73.
Too low, try again!!!!
Guess a number between 73 and 75.
You guessed 74.
You guessed the number in 7 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])
Middle Index of List # 1 is 57
Middle Index of List # 2 is 43
Middle Index of List # 3 is 60

Lesson 12-13 hacks

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))  
Square root of 10.0 : 3.1622776601683795

Hacks 2

x = 20
y = 100

# Set function
def addition(x,y):
    sum = x + y
    return(sum)

#Print the result
print(addition(x,y))
120
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)
Words starting with a: 1
Words starting with d: 1

Hacks 3

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:

Lesson 16 Hacks

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.

Hacks 2

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")
Welcome to the Simulations Quiz!

 True or False: Simulations will always have the same result. 
 A: True, 
 B: False
You said:  B
Correct!

 True or False: A simulation has results that are more accurate than an experiment 
 A: True, 
 B: False
You said:  B
Correct!

 True or False: A simulation can model real world events that are not practical for experiments 
 A: True, 
 B: False
You said:  A
Correct!

 Which one of these is FALSE regarding simulations 
 A: Reduces Costs, 
 B: Is safer than real life experiments, 
 C: More Efficient, 
 D: More accurate than real life experiments
You said:  D
Correct!

 Which of the following scenarios would be the LEAST beneficial to have as a simulation 
 A: A retail company wants to identify the item which sold the most on their website, 
 B: A restaurant wants to determine if the use of robots will increase efficiency, 
 C: An insurance company wants to study the impact of rain on car accidents, 
 D: A sports car company wants to study design changes to their new bike design 
You said:  A
Correct!

 Which of the following is better to do as a simulation than as a calculation 
 A: Keeping score at a basketball game, 
 B: Keeping track of how many games a person has won, 
 C: Determining the average grade for a group of tests, 
 D: Studying the impact of carbon emissions on the environment
You said:  D
Correct!
You scored:  6 /6

Hacks 3

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) 
you rolled: [12, 8, 8]

Extra Credit

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 ")
Heads!

Tails!

Heads!

Heads!

Heads!

Heads!

Tails!

Tails!

Tails!

Tails!

Heads!

Tails!

Tails!

Heads!

Tails!

Tails!

Tails!

Tails!

Tails!

Heads!

Tails!

Heads!

Heads!

Tails!

Heads!

Tails!

Heads!

Heads!

Heads!

Heads!

Heads!

Tails!

Tails!

Heads!

Tails!

Tails!

Heads!

Tails!

Tails!

Tails!

Tails!

Tails!

Tails!

Tails!

Tails!

Heads!

Tails!

Tails!

Tails!

Heads!

Tails!

Heads!

Tails!

Tails!

Tails!

Heads!

Heads!

Heads!

Tails!

Tails!

Heads!

Heads!

Tails!

Tails!

Tails!

Tails!

Tails!

Tails!

Heads!

Heads!

Tails!

Heads!

Tails!

Tails!

Tails!

Tails!

Tails!

Tails!

Heads!

Tails!

Tails!

Tails!

Tails!

Tails!

Tails!

Heads!

Tails!

Tails!

Heads!

Heads!

Heads!

Tails!

Heads!

Heads!

Heads!

Tails!

Heads!

Heads!

Tails!

Heads!


Okay, you flipped heads 40 times 

and you flipped tails 60 times 

Lesson 17-18

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.

Hacks 1

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))
Input: 3
[10, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]
Iteration count: 7

Hacks 2

car = []

car.append({
    "Make": "BMW",
    "Model": "M4 CSL",
    "Year": "2023",
})
def loop():
    for data in car:
        print(data)

loop()
{'Make': 'BMW', 'Model': 'M4 CSL', 'Year': '2023'}
car = "Make: BMW", "Model: M4 CSL", "Year: 2023"
print(car)
('Make: BMW', 'Model: M4 CSL', 'Year: 2023')

Hacks 3

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")
Current Time: 11:08 AM
Task Wake Up has been completed
Task Breakfast has been completed
Task Go to Work has been completed
Task Lunch has been completed
Task Work has been completed
Task Gym has been completed
Task Dinner has been completed
Task Sleep has been completed