3.3
Algorithms: Basically a list of steps that occur in a particular order
3 parts: Sequencing, Selection, and Iteration
We can think of this in the context of daily tasks like following a recipe, driving, or folding laundry. There are set instructions that are executed when certain conditions are met. If the conditions are not met, we move on to the next item of the list and continue with our evaluation.
Hack 1
Algorithms can be used to find factorials or even write out the Fibonacci sequence. Below, we have written an example of using algorithms to find the factorial of an integer ānā. try to improve upon the code given, or code an algorithm to find all numbers of the Fibonacci sequence below 20.
# Ask the user to input a number
user_input = input("Please enter a number: ")
# Convert the user's input to an integer
try:
n = int(user_input)
print("You entered an integer:", n)
except ValueError:
print("Invalid input. Please enter a valid integer.")
def factorial(n)
factorial = 1
for i in range(1, number + 1)
factorial *= i
File "/tmp/ipykernel_14862/3408418274.py", line 12
def factorial(n)
^
SyntaxError: expected ':'
def factorial(n):
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 number
user_input = input("Enter a list of non-negative integers (comma-separated): ")
numbers = [int(num.strip()) for num in user_input.split(',')]
# Calculate factorial
result = factorial(number)
if isinstance(result, int):
print(f"The factorial of {numbers} is: {result}")
else:
print("Invalid input. Factorial is not defined for negative numbers.") # Factorial is not defined for negative numbers
except ValueError:
print("Invalid input. Factorial is not defined for negative numbers.")
if __name__ == "__main__":
main()
# makes sure code is run directly, and executed based on the structure and flow
# runs only when the program is intended as the primary program
Enter a list of non-negative integers (comma-separated): 5,6,8
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/tmp/ipykernel_16193/538391817.py in <module>
34
35 if __name__ == "__main__":
---> 36 main()
37 # makes sure code is run directly, and executed based on the structure and flow
38 # runs only when the program is intended as the primary program
/tmp/ipykernel_16193/538391817.py in main()
22
23 # Calculate factorial
---> 24 result = factorial(number)
25
26 if isinstance(result, int):
NameError: name 'number' is not defined
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()
Enter a list of non-negative integers (comma-separated): 4,5
The factorial of 4 is: 24
The factorial of 5 is: 120