Unit 3 Section 1-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 typically have meaningful names that helps with the overall organization of the code and understanding of what is being represented by the variables
  • Some programming languages provide a variety of methods to represent data, which are referenced using variables 9Booleans, numbers, lists, and strings)
  • One form of a value is better suited for representation than another.

Units 3 section 1-2 Hacks

Questions (College Board's Essential Knowledge):

  1. 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

  1. What is the best data type to represent someone's dog's name?

A string

  1. Why is it important to give variables specific names before containing values?

So you can call them whilst writing code.

  1. What is the best way to represent someone's phone number?

You would use a string because you are not using the numbers of the phone number to compute anything.

  • In your own words, briefly explain by writing down what an assignment operator is

An Assignment operator is essentially the equal sign in coding.

  • 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.

  • What is a list?

a list is a sequence of elements with each element being a variable.

  • What is an element

elements are the items inside 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?

A 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"]
print(NamesList[1])
print(NamesList[3])
Luna
Ethan

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)1
User submitted numbers [1, 1, 1]
Plus 1
Result:  [2, 2, 2]

image

Screenshot 2022-11-29 at 2 01 23 PM

–UPDATE: fixed Steven’s hack, got 0.18/0.20 on Nathan’s hack, got 0.15/0.20 on Noor’s hack, full credit for Ederick’s hack (leniency).– Didn’t do Noor’s or Steven’s hacks and got 0.1 on Nathan’s hacks

0.93/1


Unit 3 Section 3-4 Notes

  • An algorithm is a finite set of instruction that accomplish a task, it can be expressed by natural language, diagrams, and various other ways.

  • Sequencing, selection, and iteration.

  • Every algorithm can be created by a mixture of sequencing, selection, and iteration

Unit 3 Section 3-4 Hacks

  • You will describe the different parts of an algorithm, sequencing, selection, and iteration in the image below.
  • sequencing: The order of how to do a process
  • Selection: Allows an algorithm to make a decision based on the status if a condition is met
  • Iteration: A loop of doing something again and again.

num1 = 5 num2 = num1 3 num3 = num2 / num1 (9 % 2) 4 result = (num3 % num1 + num2) % num3 3 / 5

The Answer to this algorithmic expression is 3

HACK for 3.3! CROSS WORD PUZZLE!

crossword

example of how to do it in your blog:

7 across - Baloney

Answers for the crossword puzzle

  1. Iteration
  2. Selection
  3. Sequence

MCquiz

0.9/1 on the hacks for this section


Hacks sections 5-6

  • Explain in your own words what each logical operator does
  1. Not: Not displays the exact opposite of whatever data is inputted
  2. And: And can help determine if two conditions are met
  3. Or: Can help determine if one of the conditions is met
  • Code your own scenario that makes sense for each logical operator
Running = False
result = not(Running)
print(result)
True
Money = 1000
Coins = 100
if Money >= 100 and Coins > 20:
    print("You Rich")
You Rich
Money = 1
Coins = 11
if Money <= 0 or Coins < 20:
    print("You Broke")
You Broke
  • 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.
  1. Selection: A piece of code that is determined by the output of true/false
  2. Algorithm: a process or set of rules to be followed in calculations
  3. Conditional Statement / If-Statement: a set of rules performed if a certain 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 = 15

if x % 2 == 0:
    print(x, "is even")
else:
    print(x, "is odd")
15 is odd
  • 1 extra point for each challenge that you program or pair program.
  • 0.5 points for your review ticket looking nice, or you convincing me that it does.
  • 1 point for each and any extra work you do that helps show your understanding of conditionals.

Hacks

  • Create 3 different flow charts representing nested statements and transfer them into code.
  • Create a piece of code that displays four statements instead of three. Try to do more if you can.
  • Make piece of code that gives three different recommendations for possible classes to take at a school based on two different conditions. These conditions could be if the student likes STEM or not.

day = True
night = False

if day == True:
    print("wake up")
if night == True:
    print("sleep")
else: 
    print("it is the afternoon")
wake up
it is the afternoon

Units 3.9 and 3.11 Notes


Three main components of an algorithm 1. Selection 2. Sequence 3. Iteration - Two pieces of code that look similar don't always produce the same things. - make notes in code --- developing algorithms
  • when creating an algorithm, it is good to outline its process before coding
  • it ensures that it is sequenced correctly

Units 3.9 and 3.11 Hacks

  • why is it important to know that algorithms that look different can do the same thing and that algorithms that look the same might have different results?(0.15)

This is because when you are programming, sometimes code can produce different results which is sub-optimal for you.

  • for the converted conditional to boolean conversion(0.10)
  • total: 0.25
isnight = False
isday = True
if isnight == True: 
        print("go to sleep")

else: 
    if isday == True: 
        print("Wake up and work")
Wake up and work
isnight = False
isday = True

eat = not(isnight) and isday
if eat == False:
    print ("dont eat")
if eat == True:
    print("go eat")
go eat
  • Includes both a flowchart AND natural language
  • Working code of the same algorithm
  • Incorporates selection AND/OR iteration
  • Make it creative!
goodreviews = True
afford = False
if goodreviews == True:
    print("Has good reviews")
    if afford and goodreviews == True:
        print("product is affordable, has good reviews, and you should purchase your product")
if goodreviews == False:
    print("adjust your search and click on another product")
if afford == False:
    print("adjust your search")




    
    
Has good reviews
adjust your search
import random

#sets variables for the game
num_guesses = 0
user_guess = -1
upper_bound = 100
lower_bound = 0

#generates a random number
number = random.randint(0,100)

# print(number)     #for testing purposes

print(f"I'm thinking of a number between 0 and 100.")

#Write a function that gets a guess from the user using input()
def guess():
    num = input("What number?")
    #add something here
    return num #add something here 

#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 int(guess) < int(number):
        print("Too low") #change this
        lower_bound = guess
        return lower_bound, upper_bound
    elif int(guess) > int(number):
        print("Too high") #change this
        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 100.
Too high
Guess a number between 0 and 100.
You guessed 80.
Too low
Guess a number between 80 and 100.
You guessed 87.
Too high
Guess a number between 80 and 87.
You guessed 86.
Too high
Guess a number between 80 and 86.
You guessed 84.
Too high
Guess a number between 80 and 84.
You guessed 83.
You guessed the number in 6 guesses!

  1. calculate the middle index and create a binary tree for each of these lists
    • 12, 14, 43, 57, 79, 80, 99
    • 92, 43, 74, 66, 30, 12, 1
    • 7, 13, 96, 111, 33, 84, 60
index = [12, 14, 43, 57, 79, 80, 99]
index[x].sort()
middle = int(len(index) / 2) 
print(middle)
print(index[middle])
54.857142857142854
index =[92, 43, 74, 66, 30, 12, 1]
index.sort()
middle = int(len(index) / 2) 
print(middle)
print(index[middle])
45.42857142857143
index = [7, 13, 96, 111, 33, 84, 60]
index.sort()
middle = int(len(index) / 2) 
print(middle)
print(index[middle])
57.714285714285715

  1. Using one of the sets of numbers from the question above, what would be the second number looked at in a binary search if the number is more than the middle number?

Set 2: 74

  1. Which of the following lists can NOT a binary search be used in order to find a targeted value?

    a. ["amy", "beverly", "christian", "devin"]

    b. [-1, 2, 6, 9, 19]

    c. [3, 2, 8, 12, 99]

    d. ["xylophone", "snowman", "snake", "doorbell", "author"]

    C because it is not sorted properly

Units 3.12 and 3.13 Notes


Essential Knowledge:

  • A procedure is a named set of instructions that can take in parameters and return values.
    • May be called "method" or "function" in different programming languages.
  • Parameters are independent variables used in the procedure to produce a result. It allows a procedure to execute without initially knowing specific input values.
  • Procedures can be classified as sequencing, selection, and iteration. How?

Example:

  • What is the procedure's name?
  • What are the parameters?
  • What did the procedure return?

  • To determine the result of a procedure or any code, you must follow the code line by line and see what each one does

  • Using syntax, you can determine the result by

    • function parameters
    • return value and statements
  • A return statement exits a function and instructs python to continue executing the program and to return a certain value

  • Value can be string, a tuple, or any other type that is being sent back to the main program


  • Modularity - the practice of breaking a complex program into smaller, independent parts or modules that can be used and reused in different parts of the program
  • Abstraction - the practice of hiding the details of how a particular code or system works and exposing only the essential features or functions that are necessary for other parts of the program to use
  • Duplication - having multiple duplicate code blocks, often decreasing readability and efficiency
  • Logic - the sequence of steps and operations that a computer follows to execute a program, including the specific instructions and decision-making processes built into the code

  • parameters being used to manage complexity
    • parameters storing variables
    • parameters storing arguments
  • calling functions with procedure names

    • choosing procedure names
    • calling procedures in python and javascript

    ```bash def function(a,b): # function is defined print(a+b) # prints output of variables

function(1,2) # one instance that it can be used function(2,3) # another instance


3

5

Hacks 3.12 3.13

  1. Define procedure and parameter in your own words Procedures or methods are basically the instructions of a function but are assigned to a variable. Unlike assigning a singular item to a class, you assign a set of instructions. Parameters are the part of a function that include data which allow the function to work.

Here is an example of both being put into use

num1=2
num2=3

def addition(num1, num2): #the procedure is addition, the parameters are num1 and num2
    sum = num1 + num2
    return sum

print(addition(num1, num2)) #here we are calling the function addition and printing it
5 #this is the output
  1. Paste a screenshot of completion of the quiz

  1. Define Return Values and Output Parameters in your own words Return values are the output of the procedure... It basically "returns" what the procedure does. Output Parameters are essentially the same as regular parameters
def addition(num1, num2): #the procedure is addition, the parameters are num1 and num2
    sum = num1 + num2
    return sum #this is the return function
5 #this is the return output
  1. Code a procedure that finds the square root of any given number. (make sure to call and return the function)
x = 9 #parameter

def sqrt(x):
    return math.sqrt(x)

print(sqrt(x)) #calling the function and printing
3.0

Topic 3.13 (3.B):

  1. Explain, in your own words, why abstracting away your program logic into separate, modular functions is effective

Abstracting away your program logic into separate, modular functions is effective because it helps to reduce code duplication and it is easier to manage in general.

  1. Create a procedure that uses other sub-procedures (other functions) within it and explain why the abstraction was needed (conciseness, shared behavior, etc.)
x = 4
y = 3

#find the solution to a simple arithmetic equation: 5(x+y)

def mathematics(x, y):
    sum = x + y
    return sum/5

print(mathematics(x, y))
1.4

Abstraction was necessary because it helped to reduce the clutter of the function. If I were to take sum and make another function dividing sum by 5, I would need make a block of code and I wouldn't be able to call it again when I needed to.

  1. Add another layer of abstraction to the word counter program (HINT: create a function that can count the number of words starting with ANY character in a given string -- how can we leverage parameters for this?)

Topic 3.13 (3.C):

  1. Define procedure names and arguments in your own words.
  2. Code some procedures that use arguments and parameters with Javascript and HTML (make sure they are interactive on your hacks page, allowing the user to input numbers and click a button to produce an output)
    • Add two numbers
    • Subtract two numbers
    • Multiply two numbers
    • Divide two numbers
# is a separate element in the list
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
  1. Define procedure names and arguments in your own words.

Procedure names are the names given to a method to produce an output for example:

Arguments are basically the data that is inputted into the function for example:

x = 1 # x and y are parameters that will be inputted into the procedure.
y = 2

def matematicas(x, y): #matematicas would be the procedure name.
    addition = x + y
    return addition 

print(matematicas(x,y))

3.0
  1. Code some procedures that use arguments and parameters with Javascript and HTML (make sure they are interactive on your hacks page, allowing the user to input numbers and click a button to produce an output)
    • Add two numbers
    • Subtract two numbers
    • Multiply two numbers
    • Divide two numbers


here is the extra credit

import math

def hypotenuse(leg1, leg2):
    # notice we're using this <var> * <var> syntax multiple times?
    # this has multiple drawbacks:
    # - it's repetitive and makes the code longer
    # - if we wanted to change the operator being 
    #   applied to `leg1` and `leg2`, we'd have to do it twice!
    leg1_squared = leg1 * leg1
    leg2_squared = leg2 * leg2
    return math.sqrt(leg1_squared + leg2_squared)

## VERSUS ##

# this works, but let's try to write the "squared" variable assignment statements more concisely...
def square(a):
    return a * a

def hypotenuse_abstracted(leg1, leg2):
    # not only is this shorter, but we can now:
    # - better understand the code at a glance--we know exactly 
    #   what `square` should do
    # - change the operator in a single place (`square`) rather than
    #   multiple times within this hypotenuse function
    leg1_squared = square(leg1)
    leg2_squared = square(leg2)
    return math.sqrt(leg1_squared + leg2_squared)

## EXTRA CHALLENGE ##
# is it possible to write the `hypotenuse` function in a single line?
def hypotenuse_abstracted2(leg1, leg2):
    return math.sqrt(square(leg1)+square(leg2))
  
print(hypotenuse_abstracted2(3,4)) 

assert hypotenuse(3, 4) == hypotenuse_abstracted(3, 4) == 5
5.0