Python Common Algorithms
Python Common Algorithms
Python’s for loops are a bit more versatile than pseudocode’s FOR loops.
Notably, it can loop over elements in the array directly!
0
2
4
6
8
10
0
2
4
6
8
10
Notice in the second example, we’re using array directly in the for loop. and so the variable
n gets the values in the array at each iteration. This is useful when we just want the items in
the array and not the index numbers: which is usually the case for totaling and counting.
Input validation
Input validation is a technique where you ensures that the user input is valid.
The basic pattern is:
Totaling
Totaling is used when you want to combine all values in the array into a single value.
The pattern is:
total = 0
for n in ...:
total += n
print(total)
print(total)
print(total)
Condition totaling is used when you only want certain values that passes a condition to be
counted towards the total.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example: summing up even numbers in an array
for i in range(0, len(array)):
if array[i] % 2 == 0:
total += array[i]
print(total)
Counting
Counting is very similar to totaling but instead of adding the value at every loop, it adds one at
every loop.
Basic pattern goes:
counter = 0
for i in ...:
count += 1
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Basic counting
count = 0
for i in range(0, len(array)):
count += 1
print(count)
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Counting every elements in an array that is even
count = 0
for i in range(0, len(array)):
if array[i] % 2 == 0: # Testing if element is even
count += 1
print(count)
Start with the min / max variable, initialized to the first item in the array. (For example,
array[0] )
Loop through