home..

Algorithms

3.3 to 3.4: Algorithms

3.3: Mathematical expressions:

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

# Parent function of y = 3(x+2)-4 is y = x

def parentFunction(x):
    y = x
    return (x, y)

parentFunction(4)
(4, 4)

3.3 Continued - Mathematical Operations

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

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.

def manipulate(num1, num2):
    add = num1 + num2
    subtract = num1 - num2
    multiply = num1 * num2
    divide = num1/num2

    return(add, subtract, multiply, divide)

manipulate = manipulate(1, 2)
print(manipulate)
(3, 3, 2, 0.5)

3.4: Strings

len ("APCSP")
5

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("Huang")
print(length)


# Use concat to merge your first and last name together.
concat = "Trevor" + "Huang"
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)
5
TrevorHuang
evor

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

Robot Pseudocode

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

De Morgan’s Law

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.

# Prompts user to give a positive int
userInput = input("Enter a positive integer to get the corresponding value of the fibbonacci sequence")
# converts from str to int
value = int(userInput)

def fibbonacci(x):
    # if 1 just return 0 because 0 is the 1st term
    if x == 1:
        return 0
    # if 2 just retun 1 because 1 is the 2nd term
    elif x == 2:
        return 1
    # otherwise add previous 2 terms to get current
    else:
        return fibbonacci(x - 1) + fibbonacci(x - 2)

# prints the value of the fibbonacci sequence based on user input    
print(fibbonacci(value))
34

Extra Hacks - Guess the fibbonacci

import random

# Generates a random int from 0-5
randomVal = random.randint(3, 5)
#Fibbonacci sequence function
def guessFibbonacci(x):
    if x == 1:
        return 0
    elif x == 2:
        return 1
    else:
        return fibbonacci(x - 1) + fibbonacci(x - 2)

# The answer is the corresponding term of the fibbonacci sequence to a random number 0-5    
answer = guessFibbonacci(randomVal)

# Asks the prompt
userAnswer = input("The value is " + str(answer) + " what term of the fibbonacci sequence does this correspond to?")

# converts userAnswer to a string so it can be compared
if(int(userAnswer) == randomVal):
    print("Correct!")
else:
    print("Incorrect!")
Correct!
© 2024    •  Powered by Soopr   •  Theme  Moonwalk