03: More Complex Algorithms#
An algorithm is a step-by-step procedure or set of rules designed to solve a specific problem or accomplish a particular task. In programming, algorithms are the logical sequences that transform input data into desired output.
Key Points to Focus on When Thinking About Algorithms#
Clarity: Ensure each step is clearly defined and unambiguous.
Correctness: The algorithm should solve the problem as intended for all valid inputs.
Efficiency: Consider how much time (speed) and space (memory) the algorithm uses.
Simplicity: Prefer simple, easy-to-understand solutions over unnecessarily complex ones.
Generality: Aim for algorithms that work for a wide range of inputs, not just specific cases.
Stepwise Refinement: Break down complex problems into smaller, manageable steps.
When designing or analyzing algorithms, always ask:
What is the input and expected output?
What steps are needed to transform input to output?
Are there edge cases or exceptions to handle?
Can the solution be made more efficient or readable?
## Import numpy
import numpy as np
First Algorithm: Find Multiples of 5#
Given a list of numbers, identify and print the first two numbers that are divisible by 5.
Steps:
Loop through each number in the list.
Check if the number is divisible by 5.
If it is, print the number.
Stop after finding and printing two such numbers.
## Set up the list:
randomnumbers = [2,3,5,6,10,9,8,15,2,8,10]
## Start a counter that will keep track of the number of multiples of 5 we find
counter = 0
## Loop through every number in the list "randomnumbers"
for number_i in randomnumbers:
print('Number i is ', np.str(number_i))
## If we have found less than two multiples of 5..
if counter < 2:
print('Entered decision structure for counter')
## If the number is divisible by 5, it's a multiple of 5:
if number_i % 5 == 0:
print('Number is a multiple of 5')
## Print it to the screen
print(number_i)
## Add to the counter to indicate how many multiples of 5 it has found
print('adding to counter')
counter+=1 ## Same thing as typing counter = counter + 1
Number i is 2
Entered decision structure for counter
Number i is 3
Entered decision structure for counter
Number i is 5
Entered decision structure for counter
Number is a multiple of 5
5
addin to counter
Number i is 6
Entered decision structure for counter
Number i is 10
Entered decision structure for counter
Number is a multiple of 5
10
addin to counter
Number i is 9
Number i is 8
Number i is 15
Number i is 2
Number i is 8
Number i is 10
Decision Structures#
In programming, decision structures allow us to control the flow of our code based on specific conditions. The most common structure is the if
statement, which lets us execute certain code only if a condition is true.
We can extend this logic using elif
(short for “else if”) to check multiple conditions in sequence, and else
to catch any cases that don’t match the previous conditions. This helps our programs make choices and respond differently depending on the situation.
In the next example, we’ll use an if-elif-else
structure to decide how much money to deduct from an e-wallet based on the type of lunch ordered.
# Set initial amount of money in e-wallet
money_in_e_wallet = 100
# Set the lunch order
lunch_order = 'pizza'
# Deduct money based on lunch order
if lunch_order == 'pizza':
money_in_e_wallet -= 10 # Deduct $10 for pizza
elif lunch_order == 'sushi':
money_in_e_wallet -= 20 # Deduct $20 for sushi
elif lunch_order == 'salad':
money_in_e_wallet -= 5 # Deduct $5 for salad
else:
print('Unknown lunch order, no money deducted')
# Print the remaining money in e-wallet
print('Money left in e-wallet: ', money_in_e_wallet)
Money left in e-wallet: 90
Class Practice: Summing Even Numbers#
In this exercise, you’ll practice using a for loop and conditional logic to solve a common programming problem: finding the sum of all even numbers within a specific range.
What to Do#
Write a Python program that calculates the sum of all even numbers from 0 to 100 (inclusive).
How to Think About It#
Break down the problem: What does it mean for a number to be even? How can you check this in code?
Plan your approach: Will you use a loop to check each number in the range? How will you keep track of the sum?
Consider efficiency: Is there a way to make your code more concise or efficient?
Test your solution: Make sure your program gives the correct result.
This exercise will help you practice looping, using conditionals, and working with accumulators (variables that keep a running total).
## For this, we want an array or a list that has the number 0 through 100 in it to loop over.
## To make an array, use np.arange:
## Always look online for documentation for functions!
# https://numpy.org/doc/stable/reference/generated/numpy.arange.html
numbersto100 = np.arange(101)
print(numbersto100)
## Alternative array:
altarray = np.arange(0,101,1)
print(altarray)
## We can also do this with the built in python range function,
## get an object instead of an array:
list100 = range(101)
print(list100)
## If we try and loop over list100:
for i in list100:
print(i)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99 100]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99 100]
range(0, 101)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
Practice Challenge: Find the Largest Number in a List#
Test your understanding of for loops and conditional statements with this challenge!
Your Task#
Write a Python program that finds the largest value in a list of numbers using a for loop and an if statement.
Steps to Follow#
Start with a list of numbers:
[-1, -6.5, 0, 8.8, 5.6, -8.7, 9.0, 1.3]
Use a for loop to go through each number in the list.
Use an if statement to check if the current number is larger than the largest number found so far.
Update your “largest number” variable whenever you find a new maximum.
Print the largest value at the end.
This exercise will help you practice looping, comparing values, and updating variables as you process a list.
## Define the list we are using:
maxlist = [-1,-6.5,0,8.8,5.6,-8.7,9.0,1.3]
#maxlist = [-1,-2,-3]
## Make a list/array that represents the indices of our actual list of interest:
indexlist = np.arange(len(maxlist))
## Loop through the index list:
for index_i in indexlist:
## If we are on the first item (0th position) in the list, set our maximum value to be that first item:
if index_i == 0:
## Set max value:
maxvalue = maxlist[index_i]
else:
## If the value of maxlist at this next index position is bigger than our previously set maximum value,
## we have a new max value
if maxlist[index_i] > maxvalue:
## then we change maxvalue to be the value of our new maximum:
maxvalue = maxlist[index_i]
print(maxvalue)
9.0
Summary of Key Learnings#
In this notebook, we explored foundational programming concepts and algorithmic thinking using Python:
Algorithm Design: We discussed the importance of clarity, correctness, efficiency, simplicity, generality, and stepwise refinement when creating algorithms.
Loops and Conditionals: Through practical examples, we learned how to use
for
loops andif
statements to process lists, make decisions, and control program flow.Finding Multiples and Maximums: We implemented algorithms to find the first two multiples of 5 in a list and to determine the largest number in a list using loops and conditionals.
Decision Structures: We practiced using
if-elif-else
statements to perform different actions based on variable values, such as deducting money from an e-wallet based on a lunch order.Summing Even Numbers: We calculated the sum of all even numbers from 0 to 100, reinforcing the use of loops, conditionals, and accumulators.
Hands-on Practice: Each section included exercises to apply and reinforce these concepts, building confidence in writing and analyzing basic algorithms.
These skills form the basis for solving more complex programming problems and developing efficient, readable code.