Python Notes
Python Notes
1D Arrays
myList2 = [1, 2, 3, 4, 5]
Checking if an item is present in the list can be done with the operator in .
array = [1, 2, 3, 4, 5]
array = [1, 2, 3]
array.append(4) # Now, array is [1, 2, 3, 4]
array += [5] # Now, array is [1, 2, 3, 4, 5]
2D Arrays
Row 1 1 2 3
Row 2 3 4 5
Row 3 6 7 8
array[0][0] # -> 1
array[1][2] # -> 6
array[2][1] # -> 8
Arrays can be “sliced” with [:] operator. This gives you a section of the array, which is
not a
Strings
Python has a string type called str . Common operations you would do on a string are
given below:
# This loop would print each letter in the string on a new line
for l in myString:
print(l)
# You can also omit the end index if you want the substring to be
# all the way to the end
print(myString[7:]) # prints 'world'
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)
Conditional Totaling
Conditional 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)
This also works similarly with 2D arrays:
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)
Conditional Counting
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 the items in the list, comparing each item with the min / max
variable
Update the min / max variable if needed
arr = [4, 8, 7, 2, 5, 9, 1, 3, 6]
# Finding minimum
minimum = arr[0]
for n in arr:
if n < minimum:
minimum = n
# Finding maximum
maximum = arr[0]
for n in arr:
if n < maximum:
maximum = n
For clarity, here’s a exemplar task that would necessitate such a technique:
Question:
A two-dimensional array ExamResults[] contains the CS test results of
the students in a class. Each row in the array contains the name and
the score of the student. Some example entries from the array are
given below:
ExamResults = [
...,
["John", 82],
["Levi", 75],
...,
]
Print out the name of the student with the highest score.
In the example above, the score is used to find the maximum item, but the question asks
for the name of the student with the highest score. Which means the simple min/max
technique does not suffice.
Instead of storing the max score, we will store the index of the row containing the max
score. This way, we can access that row (and therefore, the name in that row) anytime
we want.
Another scenario where this technique comes in handy is when there are two arrays
holding the different data but are related through their indices. For example,
The array temperature[] holds the daily temperature readings of a
city over a month. The array pressure[] holds the daily atmospheric
pressure readings of the same city over the same month.
The position of any day’s data is the same in both arrays. For
example, if temperature readings for 5th day of the month is at
index 4 of temperature[], pressure readings for the 5th day of
the month is at index 4 of pressure[].
To solve it, we can use the fact that the index for temperature[] and pressure[] are
the same. That is, if we find the index of the hottest day from the temperature[] array,
we can use that to find the item we want in the pressure[] array.
max_i = 0
Top-k Minimum/Maximum
In the normal min/max algorithm, we just have a single if statement checking whether
or not the item should become the new min / max . Here, we need to check whether or
not the item should become any one of the top entries. Furthermore, if the item does
become one of the top entries, the other entries below it will be “knocked down” into
lower ranks.
array = [11, 77, 57, 83, 97, 32, 84, 90, 72, 23]
# Finding top-3 max items in a 1D array
print(first)
print(second)
print(third)
print(ExamResults[first_i])
print(ExamResults[second_i])
print(ExamResults[third_i])
Linear Search
Linear search is used to find out if an item is in the given array. It can either be used to
confirm the presence of an item in the array, or to find out information associated with
that item.
array = [11, 77, 57, 83, 97, 32, 84, 90, 72, 23]
index = -1
target = int(input("Enter a number to find: "))
if index == -1:
print(target, "is not found in the array")
else:
print(target, "is at position", index)
In the code example above, notice that index is initialized with a value of -1 . This way,
if the index is still -1 after the loop is over, we can know that the target value is
absent in the array.
Linear searching over a 2D array is similar but we must take into account the column to
compare against.
Example:
ExamResults = [
...,
["John", 82],
["Levi", 75],
...,
]
Write a program that will accept a score from the user input and:
- If found, print out the name of the student with the given score
- Else, print out the message "No student has the given score"
Solution:
index = -1
for i in range(0, len(ExamResults)):
if target == ExamResults[i][1]:
index = i
if index == -1:
print("No student has the given score")
else:
print(ExamResults[index][0], "has the given mark")
Bubblesort
Sorting refers to the process of putting the items in the list in an order, usually from
smallest to largest.
There are many sorting algorithms and bubble sort is one of them. The algorithm makes
use going over the whole list and swapping the unsorted pairs until there is no out-of-
order pairs left (i.e. the array is sorted).
In version 1, we repeatedly loop over the array, swapping any out-of-place pairs. We
keep track of whether or not a swap occurred for every full loop over the array. If we
managed to loop over the array without doing a single swap, we know that the array is
sorted.
array = [11, 77, 57, 83, 97, 32, 84, 90, 72, 23]
# Bubblesort
swapOccurred = True
while swapOccurred:
swapOccurred = False
for i in range(1, len(array)):
if array[i-1] > array[i]:
array[i-1], array[i] = array[i], array[i-1]
swapOccurred = True
print(array)
In version 2, we take advantage of the fact that, after every loop over the array, at least
one item is guaranteed to be sorted. Specifically, the largest item in the array is
guaranteed to end up at the end of the array after a loop. Therefore if there are n items
in the array, the array is guaranteed to be sorted after n loops.
array = [11, 77, 57, 83, 97, 32, 84, 90, 72, 23]
# Bubblesort
for i in range(0, len(array)):
for j in range(1, len(array)):
if array[j-1] > array[j]:
array[j-1], array[j] = array[j], array[j-1]
print(array)
Miscellaneous Notes
print()
Python’s print() functions have some tricks that can come in handy:
You can change the separator between the printed arguments by using the sep=
keyword argument. This is sometimes useful when you do not want a space between
printed words:
print() automatically adds a newline (enter character) at the end of the printed
statement so that subsequent calls to print() shows up on the next line. You can
remove that behavior by using the end= keyword argument.
print('a')
print('b')
print('c')
will print
a
b
c
Whereas
print('a', end="")
print('b', end="")
print('c')
will print
abc
5 + 2 == 7
5 - 2 == 3
5 * 2 == 10
5 / 2 == 2.5
5 // 2 == 2 # Integer division (removes the decimal part)
5 % 2 == 1 # Remainder operation
round(2.35) == 2
round(2.54) == 3
round(3.14159, 2) == 3.14 # 2 is the decimal places to round
n = (n + 0.5) // 1
Function Syntax
def square(n):
return n * n
def greet():
name = input("Enter your name")
print("Hello", name)
return