You are on page 1of 16

Python Notes

Common Data Structures

1D Arrays

Python’s version for 1D arrays are known as list .


Here are some ways to create a list:

myList = [] # Empty list

myList2 = [1, 2, 3, 4, 5]

# Create a list with 5 zeroes


# i.e. myList3 = [0, 0, 0, 0, 0]
myList3 = [0] * 5

# Create a list with 5 empty strings


myList4 = [""] * 5

Checking if an item is present in the list can be done with the operator in .

array = [1, 2, 3, 4, 5]

print(3 in array) # prints True


print(6 in array) # print False

Adding items to the list can be done in different ways:

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

In Python, 2D arrays are just list s inside a list .


For example, the 2D Array
Column 1 Column 2 Column 3

Row 1 1 2 3

Row 2 3 4 5

Row 3 6 7 8

Can be represented in Python as:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Equivalently, you can also write each row on a different line.

array = [[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]

This makes it easier to read.


Since 2D arrays are just lists inside of lists, you can access each element in the 2D array
with two pairs of brackets ( [][] ).

array = [[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]

array[0] # -> [1, 2, 3]


array[1] # -> [4, 5, 6]
array[2] # -> [7, 8, 9]

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:

# You can loop over each letter in the string


myString = "Hello, world"

# This loop would print each letter in the string on a new line
for l in myString:
print(l)

# Changing into upper case


myString = "Hello, world"

print(myString.upper()) # prints 'HELLO, WORLD'


print(myString.lower()) # prints 'hello, world'
print(len(myString)) # prints 12

Substrings for python works with [:] .


The syntax is [start-index : end-index + 1]

myString = "Hello, world"


print(myString[0:5]) # prints 'Hello'
print(myString[5:7]) # prints ', '
print(myString[7:12]) # prints 'world'

# You can omit the 0 at the start


print(myString[:5]) # prints 'Hello'

# 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

Python’s for loops are a bit more versatile than pseudocode’s FOR loops.
Notably, it can loop over elements in the array directly!

Here’s a basic loop, like the one you’d write in pseudocode:

array = [0, 2, 4, 6, 8, 10]


for i in range(0, len(array)):
print(array[i])

this would print:

0
2
4
6
8
10

Here is another way of writing it:

array = [0, 2, 4, 6, 8, 10]


for n in array:
print(n)

this also prints:

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.

Looping directly over a 2D array gives us each row in order:

array = [[1, 2, 3],


[4, 5, 6],
[7, 8, 9]]

for row in array:


print(row)

the above code prints:


[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Input validation

Input validation is a technique where you ensures that the user input is valid.
The basic pattern is:

<variable> = input("Message asking to enter: ")


while <condition checking if input is WRONG>:
<variable> = input("Message asking to enter again: ")

Here are a few examples:

# Input validation for even numbers


number = int(input("Please enter an even number: "))
while number % 2 != 0:
number = int(input("The number must be even; enter again: "))
...

# Input validation for a password that must have be


# between 6 and 15 letters long.
password = input("Please enter a password:" )
while len(password) < 6 or len(password) > 15:
password = input("Please enter a password of valid length: ")

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

Here are a few examples:


array = [0, 2, 4, 6, 8, 10]
# Basic totaling
total = 0
for n in array:
total += n

print(total)

To total 2D arrays, you’d need a nested loop:

array = [[1,2,3], [4,5,6], [7,8,9]]


# Adding items in a 2-D array
total = 0
for i in range(0, len(array):
row = array[i]
for j in range(0, len(row)):
total += row[j]

print(total)

array = [[1,2,3], [4,5,6], [7,8,9]]


# Doing it the fancy way
total = 0
for row in array:
for n in row:
total += n

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:

array = [[1,2,3], [4,5,6], [7,8,9]]


# Example: summing up every even numbers in a 2D array
total = 0
for i in range(0, len(array)):
row = array[i]
for j in range(0, len(row)):
if row[j] % 2 == 0:
total += row[j]
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

Here are a few examples:

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

Conditional counting also works similarly:

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)

array = [[1,2,3], [4,5,6], [7,8,9]]


# Counting the number of even elements in 2D arrays
count = 0
for i in range(0, len(array)):
row = array[i]
for j in range(0, len(row)):
if row[j] % 2 == 0:
count += 1
print(count)

Finding Minimum and Maximum

The simplest minimum/maximum searching follows this pattern:

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

The examples are

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

Minimum/Maximum with Details


Sometimes, you want some additional “details” to be recorded along with the max/min
amount, so that you can output it later. This is commonly seen in 2D arrays where there
are some additional info associated with the highest/lowest item in the list.

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.

One straightforward solution:


Keep track of the index, not the value.

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.

max_i = 0 # Notice we initialize with 0 instead of ExamResults[0]

for i in range(0, len(ExamResults)):


if ExamResults[i][1] > ExamResults[max_i][1]: # Compare scores
max_i = i

print("Top student:", ExamResults[max_i][0])

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[].

Find the pressure readings of the hottest day.

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

for i in range(0, len(temperature)):


if temperature[i] > temperature[max_i]
max_i = i

print("Pressure on the hottest day:", pressure[max_i])

Top-k Minimum/Maximum

The “k” in top-k refers to the number of items needed to be found.


For example, a top-3 maximum question will ask you to find 3 highest items in the array.
A top-2 minimum question will ask you to find the 2 lowest items in the array etc.

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.

Below is a bunch of examples:

array = [11, 77, 57, 83, 97, 32, 84, 90, 72, 23]
# Finding top-3 max items in a 1D array

# Initialize the variables needed


first = array[0]
second = array[0]
third = array[0]

# Loop to check if each number in the list can be a top number


for n in array:
if n > first:
# Notice how each rank is knocked down one place
first, second, third = n, first, second
elif n > second:
second, third = n, second
elif n > third:
third = n

print(first)
print(second)
print(third)

# Example: Names of top 3 students in the Exam test


# This demonstrates the "storing the index" method
ExamResults = [
...,
["John", 82],
["Levi", 75],
...,
]
first_i = 0
second_i = 0
third_i = 0

for i in range(0, len(ExamResults)):


if ExamResults[i][1] > ExamResults[first_i][1]:
first_i, second_i, third_i = i, first_i, second_i
elif ExamResults[i][1] > ExamResults[second_i][1]:
second_i, third_i = i, second_i
elif ExamResults[i][1] > ExamResults[third_i][1]:
third_i = n

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.

The steps are as follows:

Initialize a variable to store the position of the element to find.


Loop over the indices of the array
Compare each item with the value to find
If found, record the position of that item

array = [11, 77, 57, 83, 97, 32, 84, 90, 72, 23]

index = -1
target = int(input("Enter a number to find: "))

for i in range(0, len(array)):


if target == array[i]:
index = i

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:

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],
...,
]

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:

target = int(input("Enter the mark to search for: "))

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

Here are two versions of the bubble-sort algorithm.

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('a', 'b', 'c') # Prints 'a b c'


print('a', 'b', 'c', sep="") # Prints abc
print('a', 'b', 'c', sep="*") # Prints 'a*b*c'

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

Maths operations in python

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

A number is rounded like this:

round(2.35) == 2
round(2.54) == 3
round(3.14159, 2) == 3.14 # 2 is the decimal places to round

A way to round the number without any function calls is:

n = (n + 0.5) // 1
Function Syntax

def square(n):
return n * n

def find_midpoint(a, b):


return (a + b) / 2

def greet():
name = input("Enter your name")
print("Hello", name)
return

You might also like