Python Summary
A brief summary of Python, including some basic foundations.
immutable and mutable variable
There are two kinds of variables in Python which are immutable and mutable variable. As for immutable variables, some common type like int, float, string, tuple and set. And in terms of mutable variables, it includes dict and list.
We can not change the elements in immutable variables : 1
2
3sample_sentence = "This is a sentence"
sample_sentence[2] = '5'
TypeError: 'str' object does not support item assignment
However, we can modify the mutable variables : 1
2
3
4sample_list = ['This', 'is', 'a', 'sentence']
sample_list[2] = 'A'
print(' '.join(sample_list))
This is A sentence
According to this feature of the two above kind of vairables, we can use them in the parameters in functions. There's no return statement in the function, but the original list has been modified since the list type is mutable, and the reference is delivered in Python : 1
2
3
4
5
6
7def test_func(sample):
    sample[2] = 'A'
sample_list = ['This', 'is', 'a', 'sentence']
test_func(sample_list)
print(' '.join(sample_list))
This is A sentence
As for the immutable variables, the situation is not similar with the above function. Since the type string is immutable, Python will create a new variable to store the parameters and copy the value of the original variables : 1
2
3
4
5
6
7
8def test_func(sample):
    sample = list(sample)
    sample[2] = 'A'
sample_sentence = 'This is s sentence'
test_func(sample_sentence)
print(sample_sentence)
This is a sentence
Collective Data Types
Set
A data type for representing a collection of unique, unordered items.
Creating set
- An empty set: - a_set = set()
- A set with a number of items: - a_set = {"one", 2}
- Build a set from a list: - a_set = set([1, 2, 2, 3])
Adding new items to a set
- Syntax: a_set.add('c')
Removing items from a set
- remove(): accept one argument indicating the item to be removed; raise KeyError if the item does not exist
- discard(): similar to remove(); does not raise KeyError if item does not exist
- pop(): select an arbitrary item to remove and return it
- clear(): remove all the items from a set in place
Set operations
- Union: - a_set.union(b_set), a_set | b_set
- Intersection: - a_set.intersection(b_set), a_set & b_set
- Difference: - a_set.difference(b_set), a_set - b_set
- Symmetric difference: - a_set.symmetric_difference (b_set), a_set ^ b_set
Dictionary
A mapping data type that associates a key with a value, keys must be immutable types; values can be of any data type, 3ach data item is represented as key:value.
Creating dictionary
- An empty dictionary: - a_dict = {}or- a_dict = dict()
- A dictionary with a number of items: - a_dict = {'one':1, 'two':2}
- Build a dictionary from a list of tuples: - a_dict = dict([('a',1), ('b',1)])
Adding new items to a dictionary
- Syntax: - a_dict[new_key] = new_value
- If new_key presents in the dictionary, the existing value associated to this key is updated to new_value 
Removing items from a dictionary
- Syntax: del a_dict[a_key]
Checking for a key in a dictionary
- Syntax: a_key in a_dictora_key not in a_dict
File Operation
The open(file, mode) function will open the specific file in the specific mode : 
Open modes for file writing :
- open(file_handle, 'w'): overwrite the existing content of the output file with the new content
- open(file_handle, 'a'): append the new content at the end of the output file
Writing lines to a file : * file_handle.write(the_line): write one line at a time to the file
Reading line by line : 1
2
3
4
5
6
7
8
9
10with open(file, 'a') as file_handle:
    lines = file_handle.readlines()
    for line in lines:
        print(line)
        
with open(file, 'a') as file_handle:
    line = file_handle.readline()
    while line:
        print(line)
        line = file_handle.readline()
Simple Stack
| 1 | class Stack: | 
Simple Queue
| 1 | class Queue: | 
Queue with capacity : 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
30class Queue:
    def __init__(self, size):
        self.the_queue = [0] * size
        self.count = 0
        self.front = 0
        self.rear = len * (self.the_queue) - 1
    def __len__(self):
        return self.count
    def is_empty(self):
        return len(self) == 0
    
    def is_full(self):
        return len(self) == len(self.the_queue)
    
    def append(self, item):
        assert not self.is_full(), "Can not append to a full queue"
        self.rear += (self.rear + 1) % len(self.the_queue)
        self.the_queue[self.rear] = item
        self.count += 1
    def serve(self):
        assert not self.is_empty(), "Can not serve an empty queue"
        item = self.the_queue[self.front]
        del self.the_queue[self.front]
        self.front = (self.front + 1) % len(self.the_queue)
        self.count -= 1
        
        return item
Random Module
- random(): return a random floating point number in the range [0.0, 1.0)
- randint(a, b): return a random integer in the range [a, b]
Simple Search Algorithms
Linear Searching
| 1 | def linear(target): | 
- Best case: 1 operation 
- Worst case: n operations 
Binary Seacrching
Time complexity: \(O(logn)\)
| 1 | def binary(target): | 
Simple Sorting Algorithms
Bubble Sort
Time complexity: \(O(n^2)\) 1
2
3
4
5
6
7
8def bubble_sort(the_list):
    for i in range(len(the_list) - 1):
        for j in range(len(the_list) - i - 1):
            if the_list[j] > the_list[j+1]:
                temp = the_list[j]
                the_list[j] = the_list[j+1]
                the_list[j+1] = temp
    return the_list
Selection Sort
Time complexity: \(O(n^2)\) 1
2
3
4
5
6
7
8
9
10
11
12def selection_sort(the_list):
    for i in range(len(the_list) - 1):
        smallest = i
        for j in range(i, len(the_list)):
            if the_list[j] < the_list[smallest]:
                smallest = j
        
        temp = the_list[i]
        the_list[i] = the_list[smallest]
        the_list[smallest] = temp
    
    return the_list
Insertion Sort
Time complexity: \(O(n^2)\) 1
2
3
4
5
6
7
8
9
10def insertion_sort(the_list):
    for i in range(1, len(the_list)):
        current = the_list[i]
        pos = i
        while pos > 0 and the_list[pos-1] > current:
            the_list[pos] = the_list[pos-1]
            pos -= 1
        the_list[pos] = current
    
    return the_list
Testing
| 1 | def calculate_GPA(grade_list): | 
Exception Handling
| 1 | try: | 
Recursion
Recursive Binary Search
| 1 | def rec_binary_search(the_list, target): | 
Merge Sort
| 1 | def merge_sort(the_list): | 
Quick Sort
| 1 | def quick_sort(the_list): |