├── 1. Algorithms and Design
├── *Notes for Exams.pdf
├── Code
│ ├── Array - Shift Elements.py
│ ├── Check_Digit.py
│ ├── Check_String.py
│ ├── Data Structures
│ │ ├── Binary_Search_Tree_Array.py
│ │ ├── Binary_Search_Tree_Dir.py
│ │ ├── Binary_Search_Tree_Guide.py
│ │ ├── Dictionary.py
│ │ ├── Linked_List_Array.py
│ │ ├── Linked_List_Dir.py
│ │ ├── Queue_Circular_Array.py
│ │ ├── Queue_Linear_Array.py
│ │ ├── Queue_Linked.py
│ │ ├── Stack_Array.py
│ │ └── Stack_Linked.py
│ ├── DirAccess.py
│ ├── ExtractString.py
│ ├── Searching
│ │ ├── Binary_Search_Iterative.py
│ │ ├── Binary_Search_Recursive.py
│ │ ├── Hash_Table_Search_Chaining.py
│ │ ├── Hash_Table_Search_Linear_Probing.py
│ │ └── Sequential_Search.py
│ ├── Sieve of Eratosthenes - Prime Num.py
│ └── Sorting
│ │ ├── BubbleSort.py
│ │ ├── InsertionSort.py
│ │ ├── QuickSort.py
│ │ └── SelectionSort.py
├── Control Statements.pdf
├── Data Flow Diagrams.pdf
├── Data Representation.pdf
├── Data Structures (Abstraction).pdf
├── Data Types.pdf
├── Errors.pdf
├── Functions & Modules.pdf
├── Object Oriented Programming.pdf
├── Searching.pdf
├── Sorting.pdf
├── Useful Algorithms.pdf
└── Variables.pdf
├── 2. Interface and Interactions
├── 2.1 Interacting with Computers.pdf
├── 2.2 Interfacing Computers (Networking).pdf
└── 2.3 Interacting With Data (RDB).pdf
├── 3. Systems Engineering
├── 3.1 System Development Cycle.pdf
├── 3.2 Project Management Techniques.pdf
├── 3.3 Network Applications.pdf
├── Data Checking.pdf
└── Data Flow Diagrams.pdf
├── 9597 H2 Computing Paper.pdf
├── LICENSE
├── README.md
└── Relevant Materials
├── Notes For Professionals - Algorithms.pdf
├── Notes For Professionals - Python.pdf
├── Python Cheat Sheet Basic.py
├── Python Cheat Sheet Beginner.pdf
├── Python Combined.pdf
└── Things to take note for Paper 1.docx
/1. Algorithms and Design/*Notes for Exams.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/*Notes for Exams.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Array - Shift Elements.py:
--------------------------------------------------------------------------------
1 | from random import randint
2 |
3 | def shift(arr, old_start, new_start, length):
4 | if new_start == old_start:
5 | return arr
6 |
7 |
8 | if old_start > new_start:
9 | start_index = old_start
10 | end_index = old_start + length
11 | step = 1
12 |
13 | else:
14 | start_index = old_start + length
15 | end_index = old_start
16 | step = -1
17 |
18 | for i in range(start_index, end_index, step):
19 | arr[new_start - old_start + i] = arr[i]
20 | arr[i] = ""
21 |
22 | return arr
23 |
24 |
25 | def main():
26 | arr = [""]*20
27 | new_arr = [""]*20
28 |
29 | start = randint(0, 9)
30 | print("Original start:", start)
31 |
32 | for i in range(0, 10):
33 | num = randint(0, 100)
34 | arr[start+i] = str(num)
35 |
36 | print(arr)
37 | newstart = int(input("Enter new start: "))
38 | new_arr = shift(arr, start, newstart, 10)
39 |
40 | print(new_arr)
41 |
42 |
43 | main()
44 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Check_Digit.py:
--------------------------------------------------------------------------------
1 | #CheckDigit
2 |
3 | def checkDigit():
4 | ic = []
5 | nricDigit = ["A", "B", "C", "D","E", "F", "G", "H", "I", "Z", "J"]
6 | finDigit = ["K", "L", "M", "N", "P", "Q", "R", "T", "U", "W", "X"]
7 |
8 | NRIC = input("Enter NRIC or FIN without last letter: ")
9 | for char in NRIC:
10 | ic.append(char.upper())
11 |
12 | total = 0
13 |
14 | if ic[0] == 'T' or ic[0] == 'G':
15 | total = 4
16 |
17 | total += int(ic[1]) * 2
18 | m = 7
19 |
20 | for i in range(2,8):
21 | total += int(ic[i]) * m
22 | m -= 1
23 | digitId = 11 - (total % 11)
24 |
25 | if ic[0] == 'T' or ic[0] == 'S':
26 | digit = nricDigit[digitId - 1]
27 |
28 | elif ic[0] == "F" or ic[0] == "G":
29 | digit = finDigit[digitId - 1]
30 |
31 | print("The check digit is:", digit)
32 | print("The full IC number is: ", NRIC.upper(), digit, sep='')
33 |
34 | checkDigit()
35 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Check_String.py:
--------------------------------------------------------------------------------
1 | #check string:
2 |
3 | user = input("Please enter a string: ")
4 |
5 | if user.isalnum():
6 | print("The input contains only alphabetic letters or numerals.")
7 |
8 | if user.isalpha():
9 | print("The input contains only alphabetic letters.")
10 |
11 | if user.isdigit():
12 | print("The input contains only digits.")
13 |
14 | if user.islower():
15 | print("The input contains only lower-cased alphabetical letters.")
16 |
17 | if user.isupper():
18 | print("The input contains only upper-cased alphabetical letters.")
19 |
20 | if user.isspace():
21 | print("The input contains only spaces.")
22 |
23 | else:
24 | print("The input is an invalid string.")
25 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Binary_Search_Tree_Array.py:
--------------------------------------------------------------------------------
1 | class node:
2 | def __init__(self, data, left, right):
3 | self.data = data
4 | self.left = left
5 | self.right = right
6 |
7 |
8 | class tree:
9 | def __init__(self, MAX):
10 | self.max = MAX
11 | self.root = 0
12 | self.nextfree = 1
13 | self.tree = [None] * (self.max + 1)
14 |
15 | for i in range(1, self.max):
16 | self.tree[i] = node("", 0, i + 1)
17 | self.tree[self.max] = node("", 0, 0)
18 |
19 |
20 | def add_iterative(self, value):
21 | if self.nextfree is 0: # tree is full
22 | print("Tree is full!")
23 | return ""
24 |
25 | else:
26 | target = self.nextfree
27 | self.tree[target].data = value
28 |
29 | self.nextfree = self.tree[target].right # update next free
30 | self.tree[target].right = 0 # update curr node's right ptr
31 |
32 | if self.root is 0: # tree is empty
33 | self.root = target
34 | return ""
35 |
36 | else: # tree is not empty
37 | curr = self.root
38 | prev = curr
39 | last = ""
40 |
41 | while curr is not 0:
42 | prev = curr
43 |
44 | if value < self.tree[curr].data: # move left
45 | last = "L"
46 | curr = self.tree[curr].left
47 | else: # move right
48 | last = "R"
49 | curr = self.tree[curr].right
50 |
51 | if last is "L": # change pointer of prev node
52 | self.tree[prev].left = target
53 | else:
54 | self.tree[prev].right = target
55 |
56 |
57 |
58 | def add_recursive(self, value, curr):
59 | target = self.nextfree
60 |
61 | if self.root == 0: # tree is empty
62 | self.root = target
63 | self.tree[target].data = value
64 | self.nextfree = self.tree[target].right
65 | self.tree[target].right = 0
66 |
67 | return ""
68 |
69 | else: # tree is not empty
70 | curr_node = self.tree[curr] # assign pointer for easy references
71 |
72 | if value < curr_node.data: # compare values
73 | if curr_node.left != 0: # curr_node.left is not empty
74 | self.add_recursive(value, curr_node.left) # moves left
75 |
76 | else: # curr_node.left is empty
77 | curr_node.left = target # insert
78 | self.tree[target].data = value
79 | self.nextfree = self.tree[target].right
80 | self.tree[target].right = 0
81 |
82 | else: # compare values
83 | if curr_node.right != 0: # curr_node.right is not empty
84 | self.add_recursive(value, curr_node.right) # moves right
85 |
86 | else: # curr_node.right is empty
87 | curr_node.right = target # insert
88 | self.tree[target].data = value
89 | self.nextfree = self.tree[target].right
90 | self.tree[target].right = 0
91 |
92 |
93 | def display(self):
94 | print("Root:", self.root)
95 | print("Next free:", self.nextfree)
96 |
97 | print("{:<10}{:<10}{:<10}{:<10}".format("Index", "Left", "Data", "Right"))
98 | for i in range(1, self.max + 1):
99 | left = self.tree[i].left
100 | data = self.tree[i].data
101 | right = self.tree[i].right
102 |
103 | print("{:<10}{:<10}{:<10}{:<10}".format(i, left, data, right))
104 |
105 |
106 | def inorder(self):
107 | if self.root is 0:
108 | print("Tree is empty!")
109 | else:
110 | print("Displaying in order:")
111 | self.traverseinorder(self.root)
112 | print()
113 |
114 |
115 | def traverseinorder(self, root):
116 | if root is not 0:
117 | self.traverseinorder(self.tree[root].left)
118 | print(self.tree[root].data, end = " ")
119 | self.traverseinorder(self.tree[root].right)
120 |
121 |
122 | def getroot(self):
123 | return self.root
124 |
125 |
126 | def getnextfree(self):
127 | return self.nextfree
128 |
129 |
130 | def main():
131 |
132 | values = ["x", "m", "j", "o", "k"]
133 | max = 10
134 |
135 | '''
136 | mytree = tree(max)
137 |
138 | for value in values:
139 | mytree.add(value)
140 | mytree.display()
141 | mytree.inorder()
142 | '''
143 |
144 |
145 | mytree2 = tree(max)
146 | nextfree = mytree2.getnextfree()
147 | if nextfree == 0:
148 | print("tree is full")
149 | else:
150 | for value in values:
151 | root = mytree2.getroot()
152 | mytree2.add_recursive(value, root)
153 | mytree2.display()
154 | mytree2.inorder()
155 |
156 | main()
157 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Binary_Search_Tree_Dir.py:
--------------------------------------------------------------------------------
1 | class node:
2 | def __init__(self, data):
3 | self.data = data
4 | self.left = None
5 | self.right = None
6 |
7 |
8 | class tree:
9 | def __init__(self, MAX):
10 | self.root = None
11 | self.max = MAX
12 | self.size = 0
13 |
14 |
15 | def add(self, value):
16 | if self.size is self.max:
17 | print("Tree is full!")
18 | return ""
19 |
20 | else:
21 | if self.root is None:
22 | self.root = node(value)
23 | return ""
24 |
25 | else:
26 | curr = self.root
27 | prev = curr
28 | last = ""
29 |
30 | while curr is not None:
31 | prev = curr
32 |
33 | if value < curr.data:
34 | last = "L"
35 | curr = curr.left
36 | else:
37 | last = "R"
38 | curr = curr.right
39 |
40 | if last is "L":
41 | prev.left = node(value)
42 | else:
43 | prev.right = node(value)
44 |
45 |
46 | def add_rec(self, tree, value):
47 | if tree is None:
48 | return node(value)
49 |
50 | if value < tree.data:
51 | if tree.left is None:
52 | tree.left = node(value)
53 | else:
54 | self.add_rec(tree.left, value)
55 | else:
56 | if tree.right is None:
57 | tree.right = node(value)
58 | else:
59 | self.add_rec(tree.right, value)
60 |
61 |
62 | def inorder(self):
63 | if self.root is 0:
64 | print("Tree is empty!")
65 | else:
66 | print("Displaying in order:")
67 | self.traverseinorder(self.root)
68 | print()
69 |
70 |
71 | def traverseinorder(self, root):
72 | if root is not None:
73 | self.traverseinorder(root.left)
74 | print(root.data, end = " ")
75 | self.traverseinorder(root.right)
76 |
77 |
78 | def main():
79 | max = 10
80 | mytree = tree(max)
81 |
82 | values = ["x", "m", "j", "o", "k"]
83 |
84 | for value in values:
85 | mytree.add(value)
86 |
87 | mytree.inorder()
88 |
89 | main()
90 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Binary_Search_Tree_Guide.py:
--------------------------------------------------------------------------------
1 | # A Binary Search Tree (BST) Example
2 |
3 | #====================================================================================
4 | class TreeNode:
5 | def __init__(self, value):
6 | self.value = value
7 | self.left = None
8 | self.right = None
9 |
10 |
11 | #====================================================================================
12 | class BSTree: # binary serach tree
13 |
14 | def __init__(self):
15 | # initializes the root
16 | self.root = None
17 |
18 |
19 | #--------------------------------------------------------------------------------
20 | # Adds new nodes (Recursive)
21 | def insert_rec(self, tree, value):
22 | if self.root is None:
23 | self.root = Node(value)
24 | return ""
25 |
26 | if tree is None:
27 | return Node(value)
28 |
29 | elif tree.value == value:
30 | print("Duplicate value already exists in tree!")
31 | return ""
32 |
33 | elif value < tree.value:
34 | node = self.insert_rec(tree.left, value)
35 | tree.left = node
36 | return node
37 |
38 | else:
39 | node = self.insert_rec(tree.right, value)
40 | tree.right = node
41 | return node
42 |
43 |
44 | """ Alternative:
45 |
46 | if self.root is None:
47 | self.root = Node(value)
48 | return ""
49 |
50 | if tree.value == value:
51 | raise Error("Duplicate value already exists in tree!")
52 |
53 | elif value < tree.value:
54 | if tree.left is None:
55 | tree.left = Node(value)
56 | else:
57 | self.insert_rec(tree.left, value)
58 |
59 | else:
60 | if tree.right is None:
61 | tree.right = Node(value)
62 | else:
63 | self.insert_rec(tree.right, value)
64 |
65 | """
66 |
67 |
68 | #--------------------------------------------------------------------------------
69 | # Adds new nodes (Non-recursive)
70 | def insert(self, tree, value):
71 | curr = self.root
72 | prev = None
73 | last = ""
74 |
75 | while curr.value is not None:
76 | if value < curr.value:
77 | prev = curr
78 | curr = curr.left
79 | last = "L"
80 | elif value > curr.value:
81 | prev = curr
82 | curr = curr.right
83 | last = "R"
84 | else:
85 | raise Error("Duplicate value already exists in tree!")
86 |
87 | if last == "L":
88 | prev.left = TreeNode(value)
89 | else:
90 | prev.right = TreeNode(value)
91 |
92 |
93 | #--------------------------------------------------------------------------------
94 | # Gets the root of the tree
95 | def getRoot(self):
96 | return self.root
97 |
98 |
99 | #--------------------------------------------------------------------------------
100 | # Looks for a value in the tree (Recursive)
101 | # Returns None if not found else returns the node found
102 | def search_rec(self, tree, target):
103 | if tree is not None:
104 | if target == tree.value:
105 | return tree
106 | elif target < tree.value:
107 | return self.search_rec(tree.left, target)
108 | else:
109 | return self.search_rec(tree.right, target)
110 |
111 |
112 | #--------------------------------------------------------------------------------
113 | # Looks for a value in the tree (Non-recursive)
114 | # Returns None if not found else returns the node found
115 | def search(self, tree, target):
116 | if self.root is None:
117 | print("Binary tree is empty.")
118 | return None
119 | else:
120 | curr = self.root
121 | found = False
122 |
123 | while curr is not None and not found:
124 | if target == curr.value:
125 | found = True
126 | return curr
127 | elif target < curr.value:
128 | curr = curr.left
129 | else:
130 | curr = curr.right
131 |
132 | return None if not found
133 |
134 |
135 | #--------------------------------------------------------------------------------
136 | # Gets the parent of the specified node to search for
137 | def getParent(self, curNode, target, parent):
138 | if curNode == None:
139 | return None
140 | elif curNode.value == target.value:
141 | return parent
142 | else:
143 | if target.value < curNode.value:
144 | return self.getParent(curNode.left, target, curNode)
145 | elif target.value > curNode.value:
146 | return self.getParent(curNode.right, target, curNode)
147 |
148 |
149 | #--------------------------------------------------------------------------------
150 | # Non-recursive deletion
151 | def delete(self, tree, target):
152 |
153 | nodeToDel = self.search(tree, target) # search for the node
154 | if nodeToDel == None:
155 | print (target,'does not exist !')
156 | return
157 |
158 | nodeParent = self.getParent(tree, nodeToDel, None) # get parent of the node to be deleted
159 |
160 | if (nodeToDel.left and nodeToDel.right) != None: # node to be deleted has two children
161 |
162 | # find predecseeor
163 | predNode = nodeToDel.left
164 | while predNode.right != None:
165 | predNode = predNode.right
166 |
167 | # set value of the node to be deleted to the value of the predecessor node
168 | nodeToDel.value = predNode.value
169 |
170 | # delete the predecessor node
171 | if nodeToDel.left == predNode :
172 | nodeToDel.left = predNode.left
173 | # del predNode # delete the predecessor node
174 | else:
175 | self.delete(nodeToDel.left, predNode.value)
176 |
177 | else: # node to be deleted has at most 1 child
178 | # set the parent left/right pointer
179 | if nodeToDel.left == None:
180 | if nodeParent.left == nodeToDel:
181 | nodeParent.left = nodeToDel.right
182 | else:
183 | nodeParent.right = nodeToDel.right
184 | else:
185 | if nodeParent.left == nodeToDel:
186 | nodeParent.left = nodeToDel.left
187 | else:
188 | nodeParent.right = nodeToDel.left
189 | # del nodeToDel # delete the node
190 |
191 |
192 | #--------------------------------------------------------------------------------
193 | # Gets the size of the tree, i.e. number of nodes
194 | def size(self, tree):
195 | if tree == None:
196 | return 0
197 | else:
198 | return self.size(tree.left) + 1 + self.size(tree.right)
199 |
200 |
201 | #--------------------------------------------------------------------------------
202 | # Gets the height of the tree
203 | def maxDepth(self, tree):
204 | if tree == None:
205 | return -1
206 | else:
207 | # computes the two depths
208 | lDepth = self.maxDepth(tree.left)
209 | rDepth = self.maxDepth(tree.right)
210 | # returns the appropriate depth
211 | return max(lDepth, rDepth) + 1
212 |
213 |
214 | #--------------------------------------------------------------------------------
215 | # Returns True if binary tree is height-balanced
216 | def isBalanced (self, tree):
217 | if tree == None:
218 | return True
219 |
220 | lh = self.maxDepth(tree.left) # height of left subtree
221 | rh = self.maxDepth(tree.right) # height of right subtree
222 |
223 | if abs(lh-rh) <= 1 and \
224 | self.isBalanced(tree.left) and \
225 | self.isBalanced(tree.right):
226 | return True
227 | else:
228 | return False
229 |
230 |
231 | #--------------------------------------------------------------------------------
232 | # Gets the minimum value
233 | def minValue(self, tree):
234 | # goes down into the left arm and returns the last value
235 | curNode = tree
236 | while curNode.left != None:
237 | curNode = curNode.left
238 | return curNode.value
239 |
240 |
241 | #--------------------------------------------------------------------------------
242 | # Gets the maximum value
243 | def maxValue(self, tree):
244 | # goes down into the right arm and returns the last value
245 | curr = tree
246 | while curr.right is not None:
247 | curr = curr.right
248 |
249 | return curr.value
250 |
251 |
252 | #--------------------------------------------------------------------------------
253 | # Prints the tree in inOrder -- ascending order
254 | def printTree(self, tree):
255 | if tree is not None:
256 | self.printTree(tree.left)
257 | print(tree.value, end = ' ')
258 | self.printTree(tree.right)
259 |
260 |
261 | #--------------------------------------------------------------------------------
262 | # Prints the tree in preOrder
263 | def printTree_preOrder(self, tree):
264 | if tree != None:
265 | print (tree.value, end = ' ')
266 | self.printTree_preOrder(tree.left)
267 | self.printTree_preOrder(tree.right)
268 |
269 |
270 | #--------------------------------------------------------------------------------
271 | # Prints the tree in postOrder
272 | def printTree_postOrder(self, tree):
273 | def printTree(self, tree):
274 | if tree is not None:
275 | self.printTree(tree.left)
276 | self.printTree(tree.right)
277 | print(tree.value, end = ' ')
278 |
279 |
280 | #--------------------------------------------------------------------------------
281 | # Prints the tree in reverseOrder -- descending order
282 | def printTree_reverseOrder(self, tree):
283 | if tree is not None:
284 | self.printTree_reverseOrder(tree.right)
285 | print(tree.value, end = ' ')
286 | self.printTree_reverseOrder(tree.left)
287 |
288 |
289 | #====================================================================================
290 | def main():
291 | # Instantiate the binary search tree
292 | tree = BSTree()
293 |
294 | # Insert tree nodes to binary search tree
295 | numNodes = int(input("\nEnter number of tree nodes: "))
296 | print ()
297 | for i in range(1, numNodes+1):
298 | value = int(input("Enter value of node %d: " % (i)))
299 | tree.insert(tree.getRoot(), value)
300 | print ()
301 |
302 | # Delete a child
303 | value = int(input("Enter the value to be deleted: "))
304 | tree.delete(tree.getRoot(),value)
305 | print ()
306 |
307 | # Print the tree in inOrder
308 | print ('InOrder:\t', end = ' ')
309 | tree.printTree(tree.getRoot())
310 | print ()
311 |
312 | # Print the tree in preOrder
313 | print ('PreOrder:\t', end = ' ')
314 | tree.printTree_preOrder(tree.getRoot())
315 | print ()
316 |
317 | # Print the tree in postOrder
318 | print ('PostOrder:\t', end = ' ')
319 | tree.printTree_postOrder(tree.getRoot())
320 | print ()
321 |
322 | # Print the tree in reverseOrder
323 | print ('ReverseOrder:\t', end = ' ')
324 | tree.printTree_reverseOrder(tree.getRoot())
325 | print ()
326 |
327 | # Looks for a value in the tree
328 | value = int(input("\nEnter a value to find: "))
329 | if tree.search(tree.getRoot(), value) != None:
330 | print (value,'is found in the tree')
331 | else:
332 | print (value,'is not found in the tree')
333 |
334 | # Print maxDepth, maxValue, minValue and the size of the tree
335 | print ('\nMax depth:',tree.maxDepth(tree.getRoot()))
336 | print ('Max value:',tree.maxValue(tree.getRoot()))
337 | print ('Min value:',tree.minValue(tree.getRoot()))
338 | print ('Size:', tree.size(tree.getRoot()))
339 | print ()
340 |
341 | # Print whether the tree is balanced
342 | if tree.isBalanced(tree.getRoot()):
343 | print ('Tree is balanced')
344 | else:
345 | print ('Tree is not balanced')
346 |
347 | main()
348 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Dictionary.py:
--------------------------------------------------------------------------------
1 | mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3, "mike": 6}
2 |
3 | def basics():
4 | value = "d"
5 | if mydict.get(value):
6 | print("Found")
7 | else:
8 | print("{} is not found".format(value))
9 | print()
10 |
11 | print("Displaying all keys:")
12 | for k in mydict.keys():
13 | print(k)
14 | print()
15 |
16 |
17 | print("Displaying all values:")
18 | for v in mydict.values():
19 | print(v)
20 | print()
21 |
22 |
23 | print("Displaying all keys and values:")
24 | for k, v in mydict.items():
25 | print(k, v)
26 | print()
27 |
28 |
29 | print("Delete the key 'mike':")
30 | mydict.pop("mike")
31 | print(mydict)
32 | print()
33 |
34 | # Dictionaries are not sorted automatically.
35 | def sort_auto():
36 |
37 | # sort by key
38 | sorted_element_key = []
39 | print("Sort automatically by key:")
40 | for key in sorted(mydict.keys()):
41 | sorted_element_key.append([key, mydict[key]])
42 |
43 | for element in sorted_element_key:
44 | k, v = element
45 | print(k, v)
46 |
47 | print()
48 |
49 |
50 | # sort by value
51 | sorted_elements_val = []
52 | print("Sort automatically by value:")
53 | for k, v in mydict.items():
54 | sorted_elements_val.append([k, v])
55 | sorted_elements_val.sort(key = lambda x: x[1])
56 |
57 | for element in sorted_elements_val:
58 | k, v = element
59 | print(k, v)
60 |
61 | print()
62 |
63 |
64 | def sort_manual():
65 | print("Sorting manually by key:")
66 |
67 | sorted_elements = []
68 |
69 | while len(mydict.keys()) is not 0:
70 | smallest_key = None
71 | smallest_val = None
72 |
73 | for k, v in mydict.items():
74 | if smallest_key is None or smallest_val is None:
75 | smallest_key = k
76 | smallest_val = v
77 | if k < smallest_key:
78 | smallest_key = k
79 | smallest_val = v
80 |
81 | sorted_elements.append([smallest_key, smallest_val])
82 | mydict.pop(smallest_key)
83 |
84 | for element in sorted_elements:
85 | k, v = element
86 | print(k, v)
87 |
88 |
89 | def main():
90 | basics()
91 | sort_auto()
92 | sort_manual()
93 |
94 | main()
95 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Linked_List_Array.py:
--------------------------------------------------------------------------------
1 | class node:
2 | def __init__(self, data, next):
3 | self.data = data
4 | self.next = next
5 |
6 |
7 | class linkedlist:
8 | def __init__(self, MAX):
9 | self.max = MAX
10 | self.root = 0
11 | self.nextfree = 1
12 | self.linked = [None] * (self.max + 1)
13 |
14 | for i in range(1, self.max):
15 | self.linked[i] = node("", i + 1)
16 | self.linked[self.max] = node("", 0)
17 |
18 |
19 | def add(self, value):
20 | if self.nextfree is 0:
21 | print("Linked list is full!")
22 | return ""
23 |
24 | else:
25 | target = self.nextfree
26 | self.linked[target].data = value
27 | self.nextfree = self.linked[target].next
28 |
29 | if self.root is 0:
30 | self.root = target
31 | self.linked[target].next = 0
32 |
33 | else:
34 | curr = self.root
35 | prev = curr
36 |
37 | while curr is not 0 and value > self.linked[curr].data:
38 | prev = curr
39 | curr = self.linked[curr].next
40 |
41 | if curr is self.root:
42 | self.linked[target].next = self.root
43 | self.root = target
44 |
45 | else:
46 | self.linked[prev].next = target
47 | self.linked[target].next = curr
48 |
49 |
50 | def display(self):
51 | print("Root:", self.root)
52 | print("Next free:", self.nextfree)
53 | print("Printing in index order:")
54 |
55 | print("{:<10}{:<10}{:<10}".format("Index", "Data", "Next"))
56 |
57 | for i in range(1, self.max + 1):
58 | data = self.linked[i].data
59 | next = self.linked[i].next
60 | print("{:<10}{:<10}{:<10}".format(i, data, next))
61 |
62 |
63 | def traverse(self):
64 | print("Traversing in order:")
65 |
66 | curr = self.root
67 |
68 | while curr is not 0:
69 | print(self.linked[curr].data, end = " ")
70 | curr = self.linked[curr].next
71 |
72 | print()
73 |
74 | def main():
75 | mylist = linkedlist(10)
76 |
77 | values = ["m", "k", "j", "a", "x"]
78 | for value in values:
79 | mylist.add(value)
80 |
81 | mylist.display()
82 | mylist.traverse()
83 |
84 | main()
85 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Linked_List_Dir.py:
--------------------------------------------------------------------------------
1 | class node:
2 | def __init__(self, value):
3 | self.value = value
4 | self.ptr = None
5 |
6 |
7 | class linkedlist:
8 | def __init__(self):
9 | self.start = None
10 |
11 | def add(self, value):
12 | print("Adding '{}'.".format(value))
13 |
14 | if self.start is None:
15 | self.start = node(value)
16 | return ""
17 |
18 | else:
19 | curr = self.start
20 | prev = None
21 |
22 | while curr is not None and value > curr.value:
23 | prev = curr
24 | curr = curr.ptr
25 |
26 | newnode = node(value)
27 | if prev is None:
28 | newnode.ptr = self.start
29 | self.start = newnode
30 | else:
31 | newnode.ptr = prev.ptr
32 | prev.ptr = newnode
33 |
34 |
35 | def remove(self, value):
36 | if self.start is None:
37 | print("Linked list is empty!")
38 | return ""
39 |
40 | print("Removing '{}'.".format(value))
41 |
42 | curr = self.start
43 | prev = None
44 | while curr is not None and curr.value != value:
45 | prev = curr
46 | curr = curr.ptr
47 |
48 | if curr is None:
49 | print("Given value is not found!")
50 | return ""
51 |
52 | if prev is None:
53 | self.start = curr.ptr
54 | else:
55 | prev.ptr = curr.ptr
56 |
57 |
58 |
59 | def display(self):
60 | if self.start is None:
61 | print("Linked list is empty!")
62 | return ""
63 | else:
64 | print("Displaying linked list in order:")
65 | curr = self.start
66 | while curr is not None:
67 | print(curr.value)
68 | curr = curr.ptr
69 |
70 |
71 | def main():
72 | MyList = linkedlist()
73 |
74 | values = ("N", "L", "O", "A", "X")
75 | for value in values:
76 | MyList.add(value)
77 | MyList.display()
78 | MyList.remove("O")
79 | MyList.display()
80 |
81 | main()
82 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Queue_Circular_Array.py:
--------------------------------------------------------------------------------
1 | # Implementation of the Queue ADT (circular_queue) using an array.
2 |
3 |
4 | class Queue(object):
5 | """ Array-based queue implementation (circular_queue)"""
6 |
7 | DEFAULT_CAPACITY = 10 # Class variable applies to all queues
8 |
9 | def __init__(self):
10 | self.items = [None] * Queue.DEFAULT_CAPACITY
11 | self.rear = -1
12 | self.front = 0
13 | self.size = 0
14 |
15 |
16 | def enqueue(self, newItem):
17 | """Adds newItem to the rear of queue.
18 | Precondition: the queue is not full."""
19 |
20 | if self.isFull():
21 | print("Queue is full!")
22 | return ''
23 | else:
24 | if self.rear == self.DEFAULT_CAPACITY - 1: #end of array
25 | self.rear = 0
26 | else:
27 | self.rear += 1
28 |
29 | self.items[self.rear] = newItem
30 | self.size += 1
31 |
32 |
33 | def dequeue(self):
34 | """Removes and returns the item at front of the queue.
35 | Precondition: the queue is not empty."""
36 |
37 | if self.isEmpty():
38 | print("Queue is empty!")
39 | return ''
40 | else:
41 | oldItem = self.items[self.front]
42 |
43 | if self.front == self.DEFAULT_CAPACITY - 1: #end of array
44 | self.front = 0
45 | else:
46 | self.front += 1 #move pointer to point to next element
47 |
48 | self.size -= 1
49 | return oldItem
50 |
51 | def peek(self):
52 | """Returns the item at front of the queue.
53 | Precondition: the queue is not empty."""
54 |
55 | if self.isEmpty():
56 | print("Queue is empty!")
57 | return ''
58 | else:
59 | return self.items[self.front]
60 |
61 |
62 | def __len__(self):
63 | """Returns the number of items in the queue."""
64 |
65 | return self.size
66 |
67 |
68 | def isEmpty(self):
69 | return self.size == 0
70 |
71 |
72 | def isFull(self):
73 | return self.size == self.DEFAULT_CAPACITY
74 |
75 |
76 | def __str__(self):
77 | """Items strung from front to rear."""
78 |
79 | result = ""
80 | temp = self.front
81 |
82 | for index in range(self.size):
83 | result += str(self.items[temp]) + " "
84 | if temp == Queue.DEFAULT_CAPACITY -1: #end of array
85 | temp = 0
86 | else:
87 | temp += 1
88 |
89 | return result
90 |
91 |
92 | #------------------------------------------------------------------#
93 |
94 | def main():
95 | q = Queue()
96 | print ("Length:", len(q))
97 | print ("Empty:", q.isEmpty())
98 | print ("Enqueue 1-10")
99 | for i in range(10):
100 | q.enqueue(i + 1)
101 | print ("Peeking:", q.peek())
102 | print ("Items (front to rear):", q)
103 | print ("Length:", len(q))
104 | print ("Empty:", q.isEmpty())
105 | print ("Enqueue 11")
106 | q.enqueue(11)
107 | print ("Dequeuing items (front to rear):", end = ' ')
108 | while not q.isEmpty(): print (q.dequeue(), end = ' ')
109 | print ("\nLength:", len(q))
110 | print ("Empty:", q.isEmpty())
111 | input('\nPlease press Enter or Return to quit the program.')
112 |
113 | main()
114 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Queue_Linear_Array.py:
--------------------------------------------------------------------------------
1 | # Implementation of the Queue ADT (linear_queue) using an array.
2 |
3 |
4 | class Queue(object):
5 | """ Array-based queue implementation (linear_queue)"""
6 |
7 | DEFAULT_CAPACITY = 10 # Class variable applies to all queues
8 |
9 | def __init__(self):
10 | self.items = [None] * Queue.DEFAULT_CAPACITY
11 | self.rear = -1
12 | self.size = 0
13 |
14 |
15 | def enqueue(self, newItem):
16 | """Adds newItem to the rear of queue.
17 | Precondition: the queue is not full."""
18 |
19 | if self.isFull():
20 | print("Queue is full!")
21 | else:
22 | self.rear += 1
23 | self.size += 1
24 | self.items[self.rear] = newItem
25 |
26 |
27 | def dequeue(self):
28 | """Removes and returns the item at front of the queue.
29 | Precondition: the queue is not empty."""
30 |
31 | if self.isEmpty():
32 | return "Queue is empty!"
33 | else:
34 | oldItem = self.items[0]
35 | for i in range(self.size-1):
36 | self.items[i] = self.items[i+1]
37 | self.rear -= 1
38 | self.size -= 1
39 | return oldItem
40 |
41 |
42 | def peek(self):
43 | """Returns the item at front of the queue.
44 | Precondition: the queue is not empty."""
45 |
46 | if self.isEmpty():
47 | return "Queue is empty!"
48 | else:
49 | return self.items[0]
50 |
51 |
52 | def __len__(self):
53 | """Returns the number of items in the queue."""
54 |
55 | return self.size
56 |
57 |
58 | def isEmpty(self):
59 | return self.size == 0
60 |
61 |
62 | def isFull(self):
63 | return self.size == self.DEFAULT_CAPACITY
64 |
65 |
66 | def __str__(self):
67 | """Items strung from front to rear."""
68 | result = ""
69 | for i in range(self.size):
70 | result += str(self.items[i]) + " "
71 | return result
72 |
73 |
74 | #------------------------------------------------------------------#
75 |
76 | def main():
77 | q = Queue()
78 | print ("Length:", len(q))
79 | print ("Empty:", q.isEmpty())
80 | print ("Enqueue 1-10")
81 | for i in range(10):
82 | q.enqueue(i + 1)
83 | print ("Peeking:", q.peek())
84 | print ("Items (front to rear):", q)
85 | print ("Length:", len(q))
86 | print ("Empty:", q.isEmpty())
87 | print ("Enqueue 11")
88 | q.enqueue(11)
89 | print ("Dequeuing items (front to rear):", end = ' ')
90 | while not q.isEmpty(): print (q.dequeue(), end = ' ')
91 | print ("\nLength:", len(q))
92 | print ("Empty:", q.isEmpty())
93 | input('\nPlease press Enter or Return to quit the program.')
94 |
95 | main()
96 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Queue_Linked.py:
--------------------------------------------------------------------------------
1 | # Implementation of the Queue ADT using a singly linked list.
2 |
3 |
4 | class Node(object):
5 | def __init__(self, data, next = None):
6 | """Instantiates a Node with default next of None"""
7 |
8 | self.data = data
9 | self.next = next
10 |
11 |
12 |
13 | class Queue(object):
14 | """ Link-based queue implementation."""
15 |
16 | def __init__(self):
17 |
18 | self.front = None
19 | self.rear = None
20 | self.size = 0
21 |
22 |
23 |
24 | def enqueue(self, newItem):
25 | """Adds newItem to the rear of queue."""
26 |
27 | newNode = Node(newItem, None)
28 |
29 | if self.size == 0:
30 | self.front = newNode
31 | else:
32 | self.rear.next = newNode
33 |
34 | self.rear = newNode
35 | self.size += 1
36 |
37 |
38 |
39 | def dequeue(self):
40 | """Removes and returns the item at front of the queue.
41 | Precondition: the queue is not empty."""
42 |
43 | if self.isEmpty():
44 | return "Queue is empty!"
45 | else:
46 | oldItem = self.front.data
47 | self.front = self.front.next
48 | if self.front is None:
49 | self.rear = None
50 |
51 | self.size -= 1
52 | return oldItem
53 |
54 |
55 |
56 | def peek(self):
57 | """Returns the item at front of the queue.
58 | Precondition: the queue is not empty."""
59 |
60 | if self.isEmpty():
61 | return "Queue is empty!"
62 | else:
63 | return self.front.data
64 |
65 |
66 |
67 | def __len__(self):
68 | """Returns the number of items in the queue."""
69 |
70 | return self.size
71 |
72 |
73 |
74 | def isEmpty(self):
75 |
76 | return self.size == 0
77 |
78 |
79 |
80 | def __str__(self):
81 | """Items strung from front to rear."""
82 |
83 | result = ""
84 | probe = self.front
85 |
86 | while probe != None:
87 | result += str(probe.data) + " "
88 | probe = probe.next
89 |
90 | return result
91 |
92 |
93 |
94 | #------------------------------------------------------------------#
95 |
96 | def main():
97 | q = Queue()
98 | print ("Length:", len(q))
99 | print ("Empty:", q.isEmpty())
100 | print ("Enqueue 1-10")
101 | for i in range(10):
102 | q.enqueue(i + 1)
103 | print ("Peeking:", q.peek())
104 | print ("Items (front to rear):", q)
105 | print ("Length:", len(q))
106 | print ("Empty:", q.isEmpty())
107 | print ("Enqueue 11")
108 | q.enqueue(11)
109 | print ("Dequeuing items (front to rear):", end = ' ')
110 | while not q.isEmpty(): print (q.dequeue(), end = ' ')
111 | print ("\nLength:", len(q))
112 | print ("Empty:", q.isEmpty())
113 | input('\nPlease press Enter or Return to quit the program.')
114 |
115 | main()
116 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Stack_Array.py:
--------------------------------------------------------------------------------
1 | # Implementation of the Stack ADT using an array.
2 |
3 | class Stack() :
4 |
5 | """ Array-based stack implementation """
6 |
7 | DEFAULT_CAPACITY = 10 # Class variable applies to all stacks
8 |
9 | # Creates an empty stack.
10 | def __init__(self):
11 | self.theItems = [None]*Stack.DEFAULT_CAPACITY
12 | self.size= 0
13 | self.top = -1
14 |
15 |
16 | # Returns True if the stack is empty or False otherwise.
17 | def isEmpty(self):
18 | if self.top == -1: #or self.size == 0
19 | return True
20 | else:
21 | return False
22 |
23 |
24 | # Returns True if the stack is full or False otherwise.
25 | def isFull(self):
26 | return self.size == Stack.DEFAULT_CAPACITY
27 |
28 |
29 | # Returns the number of items in the stack.
30 | def __len__ (self):
31 | return self.size
32 |
33 |
34 | # Returns the top item on the stack without removing it.
35 | def peek(self):
36 | if self.isEmpty():
37 | return "Stack is empty!"
38 | else:
39 | return self.theItems[self.top]
40 |
41 |
42 | # Removes and returns the top item on the stack.
43 | def pop(self):
44 | if self.isEmpty():
45 | return "Stack is empty!"
46 | else:
47 | oldItem = self.theItems[self.top]
48 | self.top -= 1
49 | self.size -= 1
50 | return oldItem
51 |
52 |
53 | # Push an item onto the top of the stack.
54 | def push(self, item):
55 | if self.isFull():
56 | return "Stack is full!"
57 | else:
58 | self.top += 1
59 | self.theItems[self.top] = item
60 | self.size += 1
61 |
62 |
63 | def main():
64 |
65 | s = Stack()
66 |
67 |
68 | print ("Length:", len(s))
69 | print ("Empty:", s.isEmpty())
70 | print ("Popping items (top to bottom):", end = ' ')
71 | print (s.pop())
72 |
73 |
74 | print ('--------------------------------------')
75 | print ("Push 1-10")
76 | for i in range(10):
77 | s.push(i + 1)
78 | print ("Peeking:", s.peek())
79 | print ("Length:", len(s))
80 | print ("Empty:", s.isEmpty())
81 |
82 |
83 | print ('--------------------------------------')
84 | print ("Push 11")
85 | s.push(11)
86 | print ("Popping items (top to bottom):", end = ' ')
87 | while not s.isEmpty():
88 | print (s.pop(), end = ' ')
89 | print ("\nLength:", len(s))
90 | print ("Empty:", s.isEmpty())
91 |
92 | main()
93 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Data Structures/Stack_Linked.py:
--------------------------------------------------------------------------------
1 | # Implementation of the Stack ADT using a singly linked list.
2 |
3 | # The private storage class for creating stack nodes.
4 | class StackNode :
5 | def __init__(self, item, link) :
6 | self.item = item
7 | self.next = link
8 |
9 | class Stack() :
10 | """ Link-based stack implementation."""
11 |
12 | # Creates an empty stack.
13 | def __init__(self):
14 | self.top = None
15 | self.size = 0
16 |
17 |
18 | # Returns True if the stack is empty or False otherwise.
19 | def isEmpty(self):
20 | return self.top == None
21 |
22 |
23 | # Returns the number of items in the stack.
24 | def __len__(self):
25 | return self.size
26 |
27 |
28 | # Returns the top item on the stack without removing it.
29 | def peek(self):
30 | if self.isEmpty():
31 | return "Stack is empty!"
32 | else:
33 | node = self.top
34 | return node.item
35 |
36 |
37 | # Removes and returns the top item on the stack.
38 | def pop(self):
39 | if self.isEmpty():
40 | return "Stack is empty!"
41 | else:
42 | node = self.top
43 | self.top = self.top.next
44 | self.size -= 1
45 | return node.item
46 |
47 |
48 | # Pushes an item onto the top of the stack.
49 | def push(self, item):
50 | self.top = StackNode(item, self.top)
51 | self.size += 1
52 |
53 |
54 |
55 | def main():
56 |
57 | s = Stack()
58 |
59 | print ("Length:", len(s))
60 | print ("Empty:", s.isEmpty())
61 | print ("Popping items (top to bottom):", end = ' ')
62 | print (s.pop())
63 |
64 | print ('--------------------------------------')
65 | print ("Push 1-10")
66 | for i in range(10):
67 | s.push(i + 1)
68 | print ("Peeking:", s.peek())
69 | print ("Length:", len(s))
70 | print ("Empty:", s.isEmpty())
71 |
72 | print ('--------------------------------------')
73 | print ("Push 11")
74 | s.push(11)
75 | print ("Popping items (top to bottom):", end = ' ')
76 | while not s.isEmpty():
77 | print (s.pop(), end = ' ')
78 | print ("\nLength:", len(s))
79 | print ("Empty:", s.isEmpty())
80 |
81 |
82 | main()
83 |
84 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/DirAccess.py:
--------------------------------------------------------------------------------
1 | # direct access file
2 |
3 |
4 | # create test file
5 | test = open("test.txt", 'w')
6 | for i in range(1, 5+1):
7 | test.write(str(i) * 5 + '\r\n')
8 | test.close()
9 |
10 |
11 | # read 3 lines and return pointer position
12 | test = open("test.txt", 'r')
13 | for i in range(3):
14 | print(test.readline().strip())
15 | position = test.tell()
16 | print("Position: {} bytes.".format(position))
17 |
18 | # go to the beginning
19 | test.seek(0)
20 | print(test.readline().strip())
21 | length = test.tell()
22 | print("Line length: {} bytes.".format(length))
23 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/ExtractString.py:
--------------------------------------------------------------------------------
1 | #extractstring
2 |
3 | data = "myprogram.data"
4 |
5 | a = data.find("gram")
6 | b = len("gram")
7 |
8 | print(data[a:a+b])
9 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Searching/Binary_Search_Iterative.py:
--------------------------------------------------------------------------------
1 | def Binary_Search_Iterative(array, target):
2 | low, high = 0, len(array)-1
3 |
4 | while low <= high:
5 | mid = (low + high) // 2 # choose pivot to be in the middle
6 | pivot = array[mid]
7 |
8 | if pivot == target: # target found
9 | return mid # return array index
10 |
11 | elif target < pivot: # target in lower subarray
12 | high = mid - 1 # adjust pointer
13 |
14 | else: # target in higher subarray
15 | low = mid + 1 # adjust pointer
16 |
17 | if low > high: # pointers cross -- target not found
18 | return -1 # return dummy value
19 |
20 |
21 | def main():
22 | arr = [7, 19, 33, 57, 90, 100, 195, 299]
23 | target = 33
24 |
25 | pos = Binary_Search_Iterative(arr, target)
26 | if pos == -1:
27 | print("Target not found!")
28 | else:
29 | print("Number 33 is found at array index", pos)
30 |
31 | main()
32 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Searching/Binary_Search_Recursive.py:
--------------------------------------------------------------------------------
1 | def Binary_Search_Recursive(array, target, low, high):
2 |
3 | mid = (low + high) // 2 # choose pivot value to be in the middle
4 | pivot = array[mid]
5 |
6 | if pivot == target: # target found
7 | return mid # return array index
8 |
9 | elif target < pivot: # target in lower subarray
10 | return Binary_Search_Recursive(array, target, low, mid - 1)
11 | # recursively call search for lower subarray
12 |
13 | else: # target in higher subarray
14 | return Binary_Search_Recursive(array, target, mid + 1, high)
15 | # recursively call search for higher subarray
16 |
17 | if low > high: # pointers cross --> target not found
18 | return -1
19 |
20 |
21 | def main():
22 | arr = [7, 19, 33, 57, 90, 100, 195, 299]
23 | target = 33
24 |
25 | pos = Binary_Search_Recursive(arr, target, 0, len(arr))
26 |
27 | print("Number 33 is found at array index", pos)
28 |
29 |
30 | main()
31 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Searching/Hash_Table_Search_Chaining.py:
--------------------------------------------------------------------------------
1 | # collision method: chaining
2 |
3 | # hash function will be given
4 | # for this example, i will hash the ascii value of given character
5 |
6 |
7 | def GetPosition(hash_table, value):
8 | position = ord(value) % len(hash_table) # get hash value
9 |
10 | return position
11 |
12 |
13 | def AddItem(array, target):
14 | pos = GetPosition(array, target) # get original position for given value
15 |
16 | if array[pos] == []: # position is initially empty
17 | array[pos] = [target] # initialise first value
18 |
19 | else: # position contains some value
20 | array[pos].append(target) # append to chain
21 |
22 | return array
23 |
24 |
25 | def Search(array, target):
26 | pos = GetPosition(array, target) # get original position for given value
27 |
28 | if target in array[pos]: # check if target is at position
29 | return pos
30 |
31 | else:
32 | return -1
33 |
34 |
35 | def main():
36 | hash_table = [ [] ] * 11 # initialise 2D array as hash table
37 |
38 | add_items = ["a", "k", "g", "c", "d", "z", "n", "x"]
39 |
40 | for item in add_items:
41 | hash_table = AddItem(hash_table, item)
42 |
43 | for element in hash_table:
44 | print(element)
45 |
46 |
47 | pos = Search(hash_table, "d")
48 |
49 | print("Letter 'd' is found at array index", pos)
50 |
51 |
52 | main()
53 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Searching/Hash_Table_Search_Linear_Probing.py:
--------------------------------------------------------------------------------
1 | # collision method: linear probing
2 |
3 | # hash function will be given
4 | # for this example, i will hash the ascii value of given character
5 |
6 |
7 | def GetPosition(hash_table, value):
8 | position = ord(value) % len(hash_table) # get hash value
9 |
10 | return position
11 |
12 |
13 | def AddItem(array, target):
14 | original_pos = GetPosition(array, target) # get hashing position
15 |
16 | if array[original_pos] == None: # hashed original_position is empty
17 | array[original_pos] = target # assign target to position
18 |
19 | return array
20 |
21 | pos = (original_pos + 1) % len(array) # get new hashing position
22 |
23 | while pos != original_pos: # check for collision
24 |
25 | if array[pos] == None: # empty location found
26 | array[pos] = target
27 | return array
28 |
29 | else:
30 | pos = (pos + 1) % len(array) # increment position
31 |
32 | return -1 # array is full
33 |
34 |
35 | def Search(array, target):
36 | original_pos = GetPosition(array, target) # get hashing position
37 |
38 | if array[original_pos] == target: # target found at original hashing position
39 | return original_pos
40 |
41 | pos = (original_pos + 1) % len(array)
42 | while pos != original_pos:
43 |
44 | if array[pos] == None: # empty hashed position --> not found
45 | return -1
46 |
47 | elif array[pos] == target: # target found
48 | return pos
49 |
50 | else: # increment position
51 | pos = (pos + 1) % len(hash_table)
52 |
53 | return -1 # target not found
54 |
55 |
56 | def main():
57 | hash_table = [None] * 11
58 |
59 | add_items = ["a", "k", "g", "c", "d", "z", "n", "x"]
60 |
61 | for item in add_items:
62 | if hash_table != -1:
63 | hash_table = AddItem(hash_table, item)
64 |
65 | print(hash_table)
66 |
67 | pos = Search(hash_table, "d")
68 |
69 | print("Letter 'd' is found at array index", pos)
70 |
71 |
72 | main()
73 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Searching/Sequential_Search.py:
--------------------------------------------------------------------------------
1 | def Sequential_Search(array, target):
2 |
3 | for i in range(len(array)):
4 |
5 | if array[i] == target:
6 |
7 | return i
8 |
9 |
10 | def main():
11 | arr = [7, 19, 33, 57, 90, 100, 195, 299]
12 | target = 33
13 |
14 | pos = Sequential_Search(arr, target)
15 |
16 | print("Number 33 is found at array index", pos)
17 |
18 |
19 | main()
20 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Sieve of Eratosthenes - Prime Num.py:
--------------------------------------------------------------------------------
1 | #find all prime numbers from 0 - num
2 |
3 | from math import sqrt
4 |
5 | num = int(input("enter number: "))
6 | set = [True for i in range(num+1)]
7 |
8 | def method1(num):
9 | for m in range(2, int(sqrt(num)+1)):
10 | if set[m] == True:
11 | for n in range(m*m, num+1, m):
12 | set[n] = False
13 |
14 |
15 | def method2(num):
16 | p = 2
17 | while (p*p <= num):
18 | if set[p] == True:
19 | for i in range(p*p, num+1, p):
20 | set[i] = False
21 | p += 1
22 |
23 | print("Primes: ", end = "")
24 | for i in range(2, num+1):
25 | if set[i] == True:
26 | print(i, end = " ")
27 | print()
28 |
29 | method1(num)
30 | method2(num)
31 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Sorting/BubbleSort.py:
--------------------------------------------------------------------------------
1 | def swap(arr, i, j):
2 | temp = arr[i]
3 | arr[i] = arr[j]
4 | arr[j] = temp
5 |
6 | return arr
7 |
8 |
9 | def bubblesort(array):
10 | n = len(array)
11 |
12 | isSorted = False
13 | while not isSorted and n > 0:
14 | isSorted = True
15 |
16 | for i in range(n-1):
17 | if array[i] > array[i + 1]:
18 | array = swap(array, i, i+1)
19 | isSorted = False
20 | n -= 1
21 |
22 | return array
23 |
24 |
25 | def main():
26 | arr = [10, 98, 71, 13, 76, 34, 51, 1, 0, 69, 22, 90]
27 | sorted_arr = bubblesort(arr)
28 | print(sorted_arr)
29 |
30 | main()
31 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Sorting/InsertionSort.py:
--------------------------------------------------------------------------------
1 | def insertionsort(array):
2 | for i in range(len(array)):
3 | target = array[i]
4 | j = i
5 |
6 | while j > 0 and target < array[j-1]:
7 | array[j] = array[j-1]
8 | j -= 1
9 |
10 | array[j] = target
11 |
12 | return array
13 |
14 |
15 | def main():
16 | arr = [10, 98, 71, 13, 76, 34, 51, 1, 0, 69, 22, 90]
17 | sorted_arr = insertionsort(arr)
18 | print(sorted_arr)
19 |
20 | main()
21 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Sorting/QuickSort.py:
--------------------------------------------------------------------------------
1 | def QuickSort(array):
2 | if len(array) <= 1: # array is sorted (0 or 1 element)
3 | return array
4 |
5 | else:
6 | mid = len(arr) // 2
7 | pivot = array.pop(mid) # can be any valid value
8 | lower, higher = [], []
9 |
10 | for element in array: # partition into lower and higher arrays
11 | if element < pivot:
12 | lower.append(item)
13 |
14 | else:
15 | higher.append(item)
16 |
17 | # calls recurive function
18 | return QuickSort(lower) + [pivot] + QuickSort(higher)
19 |
20 |
21 | def main():
22 | arr = [10, 98, 71, 13, 76, 34, 51, 1, 0, 69, 22, 90]
23 | sorted_arr = QuickSort(arr)
24 | print(sorted_arr)
25 |
26 | main()
27 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Code/Sorting/SelectionSort.py:
--------------------------------------------------------------------------------
1 | #selection sort
2 | def printList(A, n):
3 | for i in range(0, n):
4 | print(A[i], end = ' ')
5 |
6 | def swap(A, i, j):
7 | temp = A[i]
8 | A[i] = A[j]
9 | A[j] = temp
10 |
11 | def selectionSort(A, n):
12 | for start in range(n):
13 | minVal = A[start]
14 | for k in range(start, n):
15 | if A[k] < minVal:
16 | minVal = A[k]
17 | minPos = k
18 | swap(A, start, minPos)
19 | print("Pass", start+1, ": ", end = '\t')
20 | printList(A, n)
21 | print()
22 |
23 | def main():
24 | A = [38, 58, 13, 15, 51, 27, 10, 19, 12, 86, 49, 67, 84, 60, 25]
25 | n = len(A)
26 |
27 | print("Original list:")
28 | printList(A, n)
29 | print("\n")
30 |
31 | print("Selection sort:")
32 | selectionSort(A, n)
33 | print()
34 |
35 | print("Sorted list:")
36 | printList(A, n)
37 | main()
38 |
--------------------------------------------------------------------------------
/1. Algorithms and Design/Control Statements.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Control Statements.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Data Flow Diagrams.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Data Flow Diagrams.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Data Representation.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Data Representation.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Data Structures (Abstraction).pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Data Structures (Abstraction).pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Data Types.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Data Types.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Errors.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Errors.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Functions & Modules.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Functions & Modules.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Object Oriented Programming.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Object Oriented Programming.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Searching.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Searching.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Sorting.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Sorting.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Useful Algorithms.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Useful Algorithms.pdf
--------------------------------------------------------------------------------
/1. Algorithms and Design/Variables.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/1. Algorithms and Design/Variables.pdf
--------------------------------------------------------------------------------
/2. Interface and Interactions/2.1 Interacting with Computers.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/2. Interface and Interactions/2.1 Interacting with Computers.pdf
--------------------------------------------------------------------------------
/2. Interface and Interactions/2.2 Interfacing Computers (Networking).pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/2. Interface and Interactions/2.2 Interfacing Computers (Networking).pdf
--------------------------------------------------------------------------------
/2. Interface and Interactions/2.3 Interacting With Data (RDB).pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/2. Interface and Interactions/2.3 Interacting With Data (RDB).pdf
--------------------------------------------------------------------------------
/3. Systems Engineering/3.1 System Development Cycle.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/3. Systems Engineering/3.1 System Development Cycle.pdf
--------------------------------------------------------------------------------
/3. Systems Engineering/3.2 Project Management Techniques.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/3. Systems Engineering/3.2 Project Management Techniques.pdf
--------------------------------------------------------------------------------
/3. Systems Engineering/3.3 Network Applications.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/3. Systems Engineering/3.3 Network Applications.pdf
--------------------------------------------------------------------------------
/3. Systems Engineering/Data Checking.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/3. Systems Engineering/Data Checking.pdf
--------------------------------------------------------------------------------
/3. Systems Engineering/Data Flow Diagrams.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/3. Systems Engineering/Data Flow Diagrams.pdf
--------------------------------------------------------------------------------
/9597 H2 Computing Paper.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/9597 H2 Computing Paper.pdf
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 9597_H2_Computing
2 | Notes for A Levels 9597 H2 Computing
3 |
4 | For education purposes only.
5 |
6 | Notes consolidated from my own knowledge, school lectures and internet sources.
7 |
8 | Pls feel free to share!
9 |
--------------------------------------------------------------------------------
/Relevant Materials/Notes For Professionals - Algorithms.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/Relevant Materials/Notes For Professionals - Algorithms.pdf
--------------------------------------------------------------------------------
/Relevant Materials/Notes For Professionals - Python.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/Relevant Materials/Notes For Professionals - Python.pdf
--------------------------------------------------------------------------------
/Relevant Materials/Python Cheat Sheet Basic.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """Basic Python Cheat Sheet by Filip Kral on 2015/02/16"""
4 |
5 | """
6 | Python is a cross-platform, interpreted, object-oriented programming language.
7 | That means you can run it on Linux, Windows, Mac, and other platforms,
8 | you don't need to compile your code to execute it because it is compiled on
9 | the fly, and you can use classes and objects.
10 |
11 | This cheat sheet summarizes the very basics of Python programming syntax.
12 | It is by no means exhaustive! For more comprehensive yet still compact reference
13 | I recommend Python Pocket Reference by Mark Lutz published by O'Reilly.
14 | And of course use standard help: http://docs.python.org/
15 |
16 | As you can see on this string, triple double-quotes indicate multi-line string.
17 | Triple double quotes are also used for documentation strings at the beginning
18 | of functions, classes, and modules.
19 | """
20 |
21 | # Anything after a hash character on the same row is a comment
22 | # (unless the hash is in a string)
23 |
24 | # The very top row of #!/usr/bin/env python is not relevant for Windows users.
25 | # On unix/linux however, it indicates which program to use to run the script.
26 |
27 |
28 | ## Data types
29 |
30 | # You do not have to declare variables, data type is inferred.
31 | #http://docs.python.org/tutorial/introduction.html#strings
32 | #http://docs.python.org/tutorial/introduction.html#numbers
33 | #http://docs.python.org/tutorial/stdlib.html#dates-and-times
34 | # Here we overwrite variable x on every line with a new value:
35 |
36 | x = 1 # integer number
37 | x = int(1) # integer number, function int() returns integer part of the argument
38 | # Do not confuse int() and round()! int(1.8) => 1, round(1.8) => 2.0
39 |
40 | x = False # boolean, can be True or False
41 |
42 | x = 1.0 # floating point number
43 | # Notice the decimal point, that makes it floating point and not integer!
44 | x = float(1.0) # floating point explicitly, same as float(1) or float('1')
45 |
46 | # Other numeric data types are Decimal and Fraction (see help for details)
47 |
48 | x = 'A string' # string, single quotes preferred but double-quotes work too
49 | x = r'Another string' # string, the r at the beginning indicates a raw string
50 | # # so special characters are read as they are without
51 | # # the need to escape them. For example:
52 | # # 'c:\\data' and r'c:\data' are the same
53 | x = r'One type of "quotes" can include the other type'
54 | x = r"That's helpful when dealing with apostrophes."
55 | # There are some other prefixes than r, see Python help for details.
56 | x = str(123456) # Function str() converts its argument to string
57 |
58 | # Slicing
59 | # Extracting parts of a variable is called slicing or subsetting.
60 | # Slicing works on most objects that have multiple elements, for example
61 | # strings (have multiple characters), lists, tuples, dictionaries. For example:
62 | x = str(123456) # x is now '123456'
63 | x[0] # '1'
64 | x[-1] # '6'
65 | x[1:3] # '23'
66 | x[3:] # '456'
67 | x[:2] # '12'
68 | x[0:6:2] # '135', generic pattern is x[from:to:step]
69 | x[::-1] # '654321'
70 |
71 | # Why objects? What are objects all about?
72 | # More details are further down, for now just know that anything in Python is
73 | # an object. Objects can have properties (data) and methods (functions).
74 | # For example strings have many methods. Here is how you call some of them:
75 | x = 'A,b,C-'
76 | x.upper() # returns 'A,B,C-'
77 | x.strip('-') # reutrns 'A,b,C'
78 | x.split(',') # returns a list ['A', 'b', 'C-']
79 |
80 | x = [1, 2, 3] # list
81 | x = list([1, 2]) # explicit declaration of a list
82 | x = [] # this is an empty list, same as calling list()
83 | x = ['Lists', "can", ['mix', 'types'], 123, 4.56] # lists can be nested
84 | # Refer to individual items by zero-based offset (e.g. x[2][0] returns 'mix')
85 | # Lists are mutable so you can change values of items (e.g. x[0] = 4)
86 |
87 | x = (1, 2, 3) # tuple
88 | x = tuple((1, 3)) # explicit declaration of a tuple
89 | x = () # this is an empty tuple, same as calling tuple()
90 | x = ('nested', ('and', 'mixed'), 'tuple', 1, 2, 3, 4) # tuples can be nested
91 | # Refer to individual items by zero-based offset, e.g. x[0] returns 'nested'
92 | # Tuples are immutable so you cannot change items, x[0] = 4 raises exception!
93 |
94 | x = {'a': 'dictionaries', 'b': 'are great', 'c': 123} # dictionary
95 | x = {1: 'keys can be mixed', 'b': 'and items too', 2: 123, 'c': 4.56}
96 | x = dict({1: 'explicit', 3: 'dictionary', 'b': 'declaration'})
97 | x = dict([[1, 'many ways to'], [3, 'create'], ['b', 'dicts']])
98 | # Refer to values in dictionaries by their keys, e.g. x['b'] returns 'dicts'
99 | # Assign new value to a key x['c'] = 'new value'
100 |
101 | x = None # x is now a reference to the empty object, i.e. to nothing
102 |
103 | ## Operators and operations
104 |
105 | # Binary operators take one argument on the left, one argument on the right,
106 | # and return a value. Convention suggests spaces around a binary operators.
107 | # One operator can have different effect depending on the types of arguments.
108 | 1 + 1 # addition; returns 2; similarily – (subtraction)
109 | 2 * 2 # multiplication; returns 4
110 | 2 ** 3 # power; returns 8
111 | 2.0 / 3.0 # division; returns 0.6666...
112 | # Note that 2 / 3 returns 0, correct division an operand to be float:
113 | # float(2) / 3 or 2 / 3.0
114 | 2.0 // 3.0 # floor division (result is rounded down); returns 0.0
115 | 4 % 3 # modulo; returns 1
116 | 'a' + 'b' # string concatenation, returns 'ab'
117 | 'a' * 3 # repetition; returns 'aaa'
118 | ['a'] + ['b'] # returns ['a', 'b'], see also list.append and list.extend methods
119 | [1] * 3 # repetition; returns [1,1,1]
120 |
121 | # Boolean and comparison operators
122 | 1 == 2 # equal to; returns False
123 | 1 != 3 # not equal to; returns True
124 | x or y # if x is False then y, else x
125 | x and y # if x is False then x, else y
126 | not x # if x is False then True, else False
127 | # Other boolean operators are >, <, >=, =<, is, is not.
128 | # Preferably use brackets to separate individual conditions to prevent
129 | # unexpected operator preference effects:
130 | (1 < 0) or (3 > 1 and 0 < 1)
131 | # which is: False or (True and True) => False or True => the result is True
132 |
133 | # Operations are executed using methods, different types have different methods.
134 | # There are plenty of methods. Just a few more examples then:
135 | 'A-string-with-dashes'.replace('-', '_') # replace dashes with underscores
136 | a_list = [1, 2] # define a new list, and now call its methods:
137 | a_list.append(3) # a_list is now [1, 2, 3]
138 | a_list.extend([4, 5]) # a_list is now [1, 2, 3, 4, 5]
139 | a_list.append([6, 7]) # a_list is now [1, 2, 3, 4, 5, [6, 7]]
140 | a_dict = {1: 'a', 2: 'dictionary'} # define a new dictionary
141 | a_dict.keys() # returns [1, 2]
142 | a_dict.items() # returns ['a', 'dictionary']
143 | a_dict.update({3: 'new item'}) # a_dict is now {1: 'a', 2: 'dictionary', 3: 'new item'}
144 | a_dict.get(1, 2) # returns 'a', would return 2 if 1 was an invalid key
145 |
146 |
147 | ## Program flow - code structure and code blocks
148 |
149 | # In many languages, blocks of code are surrounded by brackets,
150 | # usually by curly brackets {}, but Python is different.
151 | # In Python, blocks of code are defined by indentation!
152 | # By convention, four spaces define an indentation of a block.
153 | # It is important to be consistent!
154 | # Python interpreter is very sensitive to inappropriate indentation.
155 |
156 | ## Branching (executing blocks of codes depending on a condition)
157 |
158 | # Examples below use print function to print things to the console.
159 |
160 | # full branching example
161 | x = 1
162 | if x < 0:
163 | print('This block will execute if x is lower than zero.')
164 | elif x == 0:
165 | print('This block will execute if x is exactly zero.')
166 | else:
167 | print('This will execute if any of the above is true.')
168 |
169 | # basic branching example
170 | if x is None:
171 | print('This will execute if x is an empty reference')
172 | else:
173 | print('And... this will print to console in other cases.')
174 |
175 | # simple branching example
176 | if x > 0:
177 | print('The simplest if block.')
178 |
179 |
180 | ## Looping (iterations)
181 |
182 | # while loops are the basics
183 | i = 0
184 | while i < 10:
185 | print('Looping is great' + str(i))
186 | i = i + 1 # don't forget to increment the counter to avoid infinite loop
187 |
188 | # for loops are often more convenient than while loops
189 | for i in [1,2,3,4]:
190 | print('Variable i goes from 1 to 4, now it is ' + str(i))
191 | print('You can iterate over various iterable variables, not just lists')
192 |
193 | # couple of tricks for looping
194 | x = 0
195 | while 1: # condition is always true (infinite loop)
196 | if x < 9:
197 | pass # pass statement does nothing but is needed to define a block
198 | elif x < 14:
199 | continue # continue statement moves onto another iteration
200 | else:
201 | break # break statement stops the closest loop
202 | x += 1 # increment variable x by one, equivalent to x = x + 1
203 |
204 |
205 | ## Functions and statements by example (an extremely reduced selection)
206 |
207 | # Built-in functions
208 | x = range(5) # x is now list of [0, 1, 2, 3, 4]
209 | len(x) # returns length of x, 5 in this case
210 | type(x) # returns type of an object, in this case
211 | min(x), max(x) # returns minimum and maximum
212 | map(len, ['applies', 'function', 'to', 'items']) # this returns [7, 8, 2, 5]
213 | zip("a" * 3, ['b', 'c', 'd']) # returns ['ab', 'ac', 'ad']
214 | dir(x) # returns list of names of properties and methods of object x
215 | dir() # returns list of names of variables
216 | del x # delete the first reachable variable x from memory
217 |
218 | ## Defining your own functions
219 |
220 | # declare function like this
221 | def myFunction(x):
222 | """Functions are declared using the def statement.
223 | Get used to writing documentation strings like this one.
224 | This function just simply returns the input unchanged."""
225 | return x
226 |
227 | # and then call a function like this
228 | y = myFunction([1, 2, 3]) # y is now [1, 2, 3]
229 |
230 | # couple of notes about arguments
231 | def secondFunction(a_list, y='my default', *args, **kwargs):
232 | """This function demonstrates different ways of passing arguments."""
233 |
234 | # a_list must be always supplied and here we assume it is a list
235 | # so we can append y, which always exists thanks to its default value
236 | a_list.append(y)
237 |
238 | # variable globList was not specified in the argument list, however...
239 | # ... Python will search in the global scope from the function call.
240 | # See help for details about scope, this is just a dirty demo.
241 | # We assume globList is a list somewhere in the scope.
242 | # Relying on global variables should be avoided in most cases.
243 | # We also assume a_list argument is a list so we can do:
244 | globList.extend(a_list)
245 |
246 | # Extra unnamed arguments are collected as a list
247 | print('There are ' + str(len(args)) + ' extra arguments without a name.')
248 | # Extra named arguments are collected as a dictionary
249 | print('Keys ' + str(kwargs.keys()) + '; items ' + str(kwargs.items()))
250 |
251 | # Functions may not return any value.
252 | # Technically, in Python, functions always return at least None.
253 | # Global variables altered within a function will remain altered.
254 | return
255 |
256 | # You can call the above function in many ways:
257 |
258 | globList = [1, 2, 3] # let's define a list outside a function first
259 |
260 | secondFunction([4, 5])
261 | # >> There are 0 extra arguments passed without a name.
262 | # >> Keys []; items []
263 | # globList is now [1, 2, 3, 4, 5, 'my default']
264 |
265 | secondFunction([6, 7], y = 'not default')
266 | # >> There are 0 extra arguments passed without a name.
267 | # >> Keys []; items []
268 | # globList is now [1, 2, 3, 4, 5, 'my default', 6, 7, 'not default']
269 |
270 | secondFunction([8, 9], 'a', 'b', c = 10, d = 11)
271 | # >> There are 1 extra arguments passed without a name.
272 | # >> Keys ['c', 'd']; items [('c', 10), ('d', 11)]
273 | # globList is now [1, 2, 3, 4, 5, 'my default', 6, 7, 'not default', 8, 9, 'a']
274 |
275 | ## Reading and writing files
276 |
277 | # An example reads lines from one file and writes them to another file.
278 | # This is an old way of handling files.
279 | readthis = r'C:\toread.txt'
280 | writethis = r'C:\towrite.txt'
281 | fread = open(readthis, 'r') # fread is now a file object ready to be read
282 | fwrite = open(writethis, 'w') # fwrite is now a file object ready to be written in
283 | # Other useful modes are 'a' for append, 'rb' for binary reading, etc.
284 | line = fread.readline() # read one line
285 | fwrite.write(line) # write line
286 | # Remember to add characters for new line like fwrite.write('abc' + '\n')
287 | # let's finish the rest quickly
288 | for line in fread:
289 | fwrite.write(line)
290 | # and close the files when done; see Exception handling for another example
291 | fread.close()
292 | fwrite.close()
293 |
294 | # The above is an old way of handling files. Below is the modern version.
295 | # Use the with statement to close files automatically even if something fails.
296 | readthis = r'C:\toread.txt'
297 | writethis = r'C:\towrite.txt'
298 | with open(readthis, 'r') as fread:
299 | with open(writethis, 'w') as fwrite:
300 | for line in fread:
301 | fwrite.write(line)
302 |
303 |
304 | ## Exception handling
305 |
306 | readthis = r"C:\toread.txt"
307 | try:
308 | # code for some risky operation like reading or writing files
309 | fread = open(fread, 'r')
310 | for line in fread:
311 | print('Just doing something with a line ' + str(line))
312 | except Exception as e:
313 | # Older versions of Python (<2.6) use syntax: "except Exception, e:".
314 | # Here you would put anything you want to do to when an error occurs.
315 | # You can have more except branches addressing different types of exceptions
316 | print('Sorry, there was an error: ' + str(e)) # notify the user via console
317 | finally:
318 | # Finally branch is for cleanup code, here we want to close the file.
319 | # First, check if variable fread exists,
320 | # if it has property "closed" and if closed is not True
321 | if 'fread' in dir() and 'closed' in dir(fread) and not fread.closed:
322 | # At this point we can close the file.
323 | # If we don't check the above, we may introduce another exception!
324 | fread.close()
325 | # The finally branch is optional,
326 | # you can leave it out altogether if you have nothing to clean up.
327 | # Use the with statement to avoid try:except:finally when handling files,
328 | # however, try:except:finally blocks are necessary many other scenarios.
329 |
330 |
331 | ## Classes and object oriented programming
332 |
333 | # Programming is about data as variables of certain data types,
334 | # mechanisms for branching and looping, and functions.
335 | # Classes (and instances of classes, i.e. objects)
336 | # encapsulate data and functions into self-contained bundles.
337 |
338 | # An example of a simple class
339 | class Point2D:
340 | """A 2D point"""
341 | def __init__(self, x, y):
342 | """Constructors are by convention called __init__.
343 | Constructor is invoked when the class is instantiated.
344 | Constructor is a type of method, all methods must
345 | receive a reference to the current object as first parameter,
346 | by convention called self, not used when methods are called.
347 | Constructors are not always necessary.
348 | """
349 | self.X = float(x) # defines a data member of the class
350 | self.Y = float(y) # defines another data member of the class
351 | # there is much more to data members (see help for details)
352 |
353 | def shift(self, dx, dy):
354 | """A method to shift the point by vector (dx, dy)"""
355 | self.X = self.X + float(dx)
356 | self.Y = self.Y + float(dy)
357 |
358 | # Instantiate an object of class Point and use its method
359 | pt = Point2D(1, 5)
360 | pt.shift(2,-1) # pt.X is now 3, pt.Y is now 4
361 |
362 | # Every object is an instance of a class. Including exceptions. Most exceptions
363 | # are derived from Exception class. Let's define a custom exception class.
364 | class MyException(Exception):
365 | """This class inherits from class Exception.
366 | Exception is a baseclass (or superclass) of class (or subclass) MyException.
367 | A class can inherit from multiple baseclasses (separated by comma).
368 | """
369 | def __init__(self, extradata):
370 | """The __init__ function runs when an object of this class is created.
371 | This is also an example of method overriding: the baseclass has its own
372 | Exception.__init__ function, but it has been overridden by this method.
373 | """
374 | # There are no real private members (properties or methods) in Python,
375 | # all members can be accessed directly. However there are conventions.
376 | self.extra = extradata # defining a data member of the class
377 | # One underscore indicates this should be treated as private member,
378 | # i.e. accessed only within the class where it is defined.'
379 | self._secret = 'Not intended for use outside of this class'
380 |
381 | def notifyUser(self):
382 | print(str(self.args)) # self.args is inherited from baseclass Exception
383 | print(str(self.message)) # also inherited from Exception
384 | print(str(len(self.extra)) + ' data items: ' + str(self.extra))
385 |
386 | # We can raise our custom exception intentionally (somewhat artificial example)
387 | try: raise MyException([1, 2, 3])
388 | except MyException as m: m.notifyUser()
389 | # prints out "() \n3 data items: [1, 2, 3]"
390 |
391 |
392 | ## Modules
393 |
394 | # Modules are collections of functions you can load using the import statement
395 | # The import statement has several forms.
396 |
397 | # import module for interaction with operating system
398 | import os
399 | a_path = r'C:\my\file.txt'
400 | filename = os.path.basename(a_path) # 'file.txt'
401 | foldername = os.path.dirname(a_path) # 'C:\my'
402 | os.path.join(foldername, filename) # 'C:\my\file.txt'
403 | os.listdir(foldername) # returns list of files in folder foldername
404 |
405 | # use the datetime module to retrieve date-time stamp
406 | import datetime
407 | t = datetime.datetime.now() # returns current computer time
408 | t.strftime('%Y%m%d%H%M%S') # formats time into a string as specified
409 |
410 | # Other useful modules are sys, shutil, math, and many others. You can create
411 | # your own modules too ( http://docs.python.org/2/tutorial/modules.html ).
412 |
413 | ## Message to R users
414 | # If you are familiar with R, Python may seem somewhat clumsy.
415 | # R is more flexible when it comes to vector operations, stats, and plotting.
416 | # Check out Python modules numpy, scipy, matplotlib, and pandas.
--------------------------------------------------------------------------------
/Relevant Materials/Python Cheat Sheet Beginner.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/Relevant Materials/Python Cheat Sheet Beginner.pdf
--------------------------------------------------------------------------------
/Relevant Materials/Python Combined.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/Relevant Materials/Python Combined.pdf
--------------------------------------------------------------------------------
/Relevant Materials/Things to take note for Paper 1.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/howtoosee/9597_H2_Computing/87baf2054a6185d23b28cb03f1e8dda6686cf8ff/Relevant Materials/Things to take note for Paper 1.docx
--------------------------------------------------------------------------------