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→ 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()
The factorial of 2 is: 2
The factorial of 0 is: 1
The factorial of 1 is: 1
The factorial of 5 is: 120
The factorial for -3 is not defined (negative input).

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!

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

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.

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")
5

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

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.

#Find the number of characters in your last name using len.
length = len("Bharadwaj")
print(length)


# Use concat to merge your first and last name together.
concat = "Aditi" + "Bharadwaj"
print (concat)


# Use Substring to show only the 3rd to 6th characters.
# be sure to start at 2 because it starts counting at 0
substring = concat[2:6]
print (substring)
9
AditiBharadwaj
itiB

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
True
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

HW Hacks

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.