3.3 to 3.4: Algorithms

3.3: Mathematical expressions:

  • Algorithm: a finite set of instructions that accomplish a specific task.
  • Ex: when you go to bake cookies you use specific steps
  • Getting ready in the morning: shirt, pants, breakfast
  • Algorithm is like a list of steps that occur in a specific/particular order.
  • Sequencing: things are done in order
  • Selection
  • Iteration
  • Selection: do first step, make decision(yes or no), step true or false( if or else)
  • Iteration/repetition→ First step, second step, continue condition, Yes or no, step to do if true
  • Ways to write algorithm: flow chart(use arrows to tell decision)
  • Pseudo code→ fake code. writing . verbal instructions/comments on what each section is doing. </span>

"Algorithm"

def factorial(n):
    # Selection
    if n < 0:
        return "Factorial is not defined for negative numbers"
    # in case negative numbers are inputted...
    elif n == 0 or n == 1:
        # "else if" sets a condition to be met, and if it is met, the code should return 1
        return 1
    else:
        result = 1
        for i in range(2, n + 1):
            #iterates through the list, from 2 to n inclusive - 1 is not counted, n*1 = n
            result *= i
            #multiplies the current value of result by i
            # i is sort of like the index, or the number assigned to each value in the list, starting from 0
        return result


def main():
    try:
        # Get user input for the numbers as a comma-separated list
        user_input = input("Enter a list of non-negative integers (comma-separated): ")
        numbers = [int(num.strip()) for num in user_input.split(',')]


        # Calculate and print factorial for each number
        for number in numbers:
            # Calculate factorial for each number, iterates through the list
            result = factorial(number)


            if isinstance(result, int):
                print(f"The factorial of {number} is: {result}")
                # Selection, makes sure the result is actually an integer before printing
            else:
                print(f"The factorial for {number} is not defined (negative input).")


    except ValueError:
        print("Invalid input. Please enter a valid list of non-negative integers.")




if __name__ == "__main__":
    main()

Popcorn Hack #1

Scenario: You’re in your math test and you forgot how to graph the parent function of 3(x+2)-4. Input a list of x-values to figure out the y-values and print the results of what you get so you can graph the function and get an A on your math test!

numbers = [0,1,3]
print(numbers[0] * 3 -2)
print(numbers[1] * 3 -2)
print(numbers[2] * 3 -2)

3.3 Continued - Mathematical Operations

  • Addition: a + b
  • Subtraction: a - b
  • Multiplication: a * b
  • Division: a / b
  • Modulus (remainder of a/b): a MOD b
  • For python it is %
  • Math in order of operations
  • MOD is held to the value of multiplication + division in PEMDAS
num1 = 40
num2 = num1 / 2
num3 = 5 * num2 + 3
result = num2 % 3 * num1 + 4 - num3 / 2
print (result)

Popcorn hack #2

What will the code below print?

num1 = 20
num2 = num1 /2 
num3 = num2 * 10 + 3
print(num3)

Popcorn hack #3:

Write a code that can add, subtract, multiply, divide, and MOD numbers. Try adding them in the same line and seeing what they do. Try adding variables to your hack #2.

num1 = 2
num2 = 1

def add(num1 + num2)

3.4: Strings

  • Strings are ordered sequence of characters (characters = numbers, letters, even space)
  • Substring is part of an existing string
  • Some procedures exist that can be used with strings, each language has its own functions
  • len (str)
  • Returns the number of characters in the string
len ("APCSP")

  • Concat
  • Merges both strings together, returns it so that they are one word </span>
concat = "AP" + "CSP"
# Concat is simply a variable
print(concat)

Popcorn hack #4:

Find the number of characters in your last name using len. Use concat to merge your first and last name together. Use Substring to show only the 3rd to 6th characters.

length = len("Tinga")
print (length)

tingus = ("Ninaad" + " Tinga")
print (tingus)

substring = tingus[2:6]
print (substring)

Palindromes

A palindrome is a string that reads the same from right to left as left to right. For example, 2112 and mom are palindromes


def palindrome(input_str):
    # Remove spaces and convert the string to lowercase
    clean_str = input_str.replace(" ", "").lower()
    # Check if the cleaned string is equal to its reverse
    return clean_str == clean_str[::-1]


print(palindrome("taco cat")) # True
print(palindrome("hi")) # False

Pseudo Code vs Python

Python

Python is a high-level programming language. When you write an algorithm in Python, you are essentially creating a set of instructions that a computer can follow to solve a specific problem.

name = "Eshika"
age = 15
print("Name:", name)
print("Age:", age)

Pseudo Code

College Board Pseudo Code is a simplified, high-level representation of an algorithm that is designed to be easy to understand. Pseudo code uses a mixture of natural language and programming-like constructs to describe the algorithm’s logic without specifying a particular programming language.

OUTPUT “Name:”, name OUTPUT “Age:”, age </span>

Robot MCQ Problems

If the robot leaves the grid, the program will end Command MOVE_FORWARD() moves the robot one block in the direction its facing Command ROTATE_LEFT() moves the robot left in place Command ROTATE_RIGHT() makes the robot do an in place right turn Command CAN_MOVE(direction) makes it so that if there is an open space in the relative direction the robot is facing, the robot goes there, can be any direction

MOVE_FORWARD()
MOVE_FORWARD()
MOVE_FORWARD()
ROTATE_LEFT()
MOVE_FORWARD()
MOVE_FORWARD()
ROTATE_RIGHT()
MOVE_FORWARD()
MOVE_FORWARD()
MOVE_FORWARD()

Logic Gates in Python:

AND gate, OR gate, NOT gate, NAND gate, NOR gate, XOR gate, and XNOR gate.

What is a logic gate?: Logic gates are used in circuits to make decisions based on a combination of digital signals beign inputed. The concept of logic gates revolves around Boolean algebra as well as binary. It is basically how zero represents the false condition and 1 represents True. Think of it as a switch where if it is at 0, the switch is turned off while if it is 1, then the lightbulb will turn on.

The AND gate requires both inputs to be 1 or true so the end output is true. In other words, the output is 1 only when both inputs one AND two are 1.

age= 15

if age>2 and type(age)==int:
    print(age)

age=13 

if age>2 and type(age)==str:
    print(age)

De Morgan’s Law

  • A way to turn statements from AND to OR by negating terms
  • not (A or B) = (not A) and (not B)
  • not (A and B) = (not A) or (not B)

HW ccc

Use an algorithm to find certain values of the Fibonacci sequence. For example, your code should output the nth index in the sequence. An example of how the sequence works is 0,1,1,2,3,5,8,13. The pattern is you add the previous 2 numbers together to get the new number.

# Function to generate the Fibonacci sequence up to a specified number of values
def generate_fibonacci(n):
    fibonacci_sequence = []
    a, b = 0, 1
    while len(fibonacci_sequence) < n:
        fibonacci_sequence.append(a)
        a, b = b, a + b
    return fibonacci_sequence

# Get the number of values from the user
try:
    n = int(input("Enter the number of Fibonacci values to generate: "))
    if n <= 0:
        print("Please enter a positive integer.")
    else:
        # Generate and print the Fibonacci sequence
        fibonacci_sequence = generate_fibonacci(n)
        print("Fibonacci Sequence:")
        for num in fibonacci_sequence:
            print(num, end=" ")
except ValueError:
    print("Invalid input. Please enter a valid positive integer.")
Fibonacci Sequence:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565