├── backtracking.pdf ├── binary_search.pdf ├── two_pointer.pdf ├── tree_questions.pdf ├── bit manipulation.pdf ├── search_strategies.pdf ├── combinatorial_search.pdf ├── decrease_and_conquer.pdf ├── heap_priority_queue.pdf ├── Python Data Structure.pdf ├── linear_data_structure.pdf ├── Abstract Data Structures.pdf ├── sorting_algorithms_with_python3.pdf ├── advanced_search_on_linear_data_structures.pdf ├── Colab Codes └── Colab Notebooks │ ├── chapter_6_linear_data_structure.ipynb │ ├── tree_search.ipynb │ ├── chapter_15_bit_manipulation.ipynb │ ├── tree_data_structure.ipynb │ ├── chapter_14_sorting_2.ipynb │ ├── suffix_array.ipynb │ ├── chapter_8_heap_priority_queue.ipynb │ ├── chapter_6_linear_data_structure.depre.ipynb │ ├── graph_search_application.ipynb │ ├── graph_search.ipynb │ ├── chapter_14_sorting.ipynb │ └── graph_data_structure.ipynb ├── README.md ├── chapter_tree_data_structure_and_traversal.ipynb ├── Advanced_Search_on_Linear_Data_Structures.ipynb └── chapter_python_comparison_sorting.ipynb /backtracking.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/backtracking.pdf -------------------------------------------------------------------------------- /binary_search.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/binary_search.pdf -------------------------------------------------------------------------------- /two_pointer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/two_pointer.pdf -------------------------------------------------------------------------------- /tree_questions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/tree_questions.pdf -------------------------------------------------------------------------------- /bit manipulation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/bit manipulation.pdf -------------------------------------------------------------------------------- /search_strategies.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/search_strategies.pdf -------------------------------------------------------------------------------- /combinatorial_search.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/combinatorial_search.pdf -------------------------------------------------------------------------------- /decrease_and_conquer.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/decrease_and_conquer.pdf -------------------------------------------------------------------------------- /heap_priority_queue.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/heap_priority_queue.pdf -------------------------------------------------------------------------------- /Python Data Structure.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/Python Data Structure.pdf -------------------------------------------------------------------------------- /linear_data_structure.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/linear_data_structure.pdf -------------------------------------------------------------------------------- /Abstract Data Structures.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/Abstract Data Structures.pdf -------------------------------------------------------------------------------- /sorting_algorithms_with_python3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/sorting_algorithms_with_python3.pdf -------------------------------------------------------------------------------- /advanced_search_on_linear_data_structures.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ashishpatel26/Algorithms-and-Coding-Interviews/master/advanced_search_on_linear_data_structures.pdf -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/chapter_6_linear_data_structure.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"Untitled","version":"0.3.2","views":{},"default_view":{},"provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"cell_type":"code","execution_count":0,"metadata":{},"outputs":[],"source":[""]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/tree_search.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"tree_search.ipynb","version":"0.3.2","provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"-N44hhD6CqRT","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"8xckq2iGCtG8","colab_type":"text"},"cell_type":"markdown","source":["## DFS tree search"]},{"metadata":{"id":"dw0xDCnDCyLo","colab_type":"text"},"cell_type":"markdown","source":["### A general purpose search"]},{"metadata":{"id":"c9xcMvZxC0zK","colab_type":"code","colab":{}},"cell_type":"code","source":["def dfs(t, s):\n"," '''implement the dfs recursive of tree'''\n"," print(s)\n"," for neighbor in t[s]:\n"," dfs(t, neighbor)\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"pOnCVL5eDIh-","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":121},"outputId":"7c437d60-4881-4eea-b4ba-c9675519a7e2","executionInfo":{"status":"ok","timestamp":1551054538760,"user_tz":480,"elapsed":403,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["t = {1: [2, 3], 2: [4, 5],\n"," 3: [], 4: [6], 5: [], 6: []}\n","dfs(t, 1)"],"execution_count":4,"outputs":[{"output_type":"stream","text":["1\n","2\n","4\n","6\n","5\n","3\n"],"name":"stdout"}]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/chapter_15_bit_manipulation.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"chapter_15_bit_manipulation.ipynb","version":"0.3.2","provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"6HDn2LSnUIhV","colab_type":"code","colab":{}},"cell_type":"code","source":["\n","'''built-in functions'''\n","print(bin(1), bin(-1))\n","print(bin(126), bin(-126))\n","a = bin(88)\n","a1 = bin(-88)\n","print(a)\n","print(a1)\n","b = int('01011000', 2)\n","c = int('88', 10)\n","print(b, c)\n","\n","d = chr(88)\n","print(d)\n","\n","e = ord('a')\n","print(e)\n","\n","empty_bytes = bytes(4)\n","print(type(empty_bytes))\n","print(empty_bytes)\n","\n","# Cast bytes to bytearray\n","mutable_bytes = bytearray(b'\\x00\\x0F')\n","\n","# Bytearray allows modification\n","mutable_bytes[0] = 255\n","mutable_bytes.append(255)\n","print(mutable_bytes)\n","\n","# Cast bytearray back to bytes\n","immutable_bytes = bytes(mutable_bytes)\n","print(immutable_bytes)\n","\n","# Some bytes to play with\n","byte1 = int('11110000', 2) # 240\n","byte2 = int('00001111', 2) # 15\n","byte3 = int('01010101', 2) # 85\n","\n","# Ones Complement (Flip the bits)\n","print(~byte1)\n","\n","# AND\n","print(byte1 & byte2)\n","\n","# OR\n","print(byte1 | byte2)\n","\n","# XOR\n","print(byte1 ^ byte3)\n","\n","# Shifting right will lose the right-most bit\n","print(byte2 >> 3)\n","\n","# Shifting left will add a 0 bit on the right side\n","print(byte2 << 1)\n","\n","# See if a single bit is set\n","bit_mask = int('00000001', 2) # Bit 1\n","print(bit_mask & byte1) # Is bit set in byte1?\n","print(bit_mask & byte2) # Is bit set in byte2?\n","\n","'''Combined bit manipulation'''\n","def get_bit(val, i):\n"," mask = 1 << i\n"," if val & mask:\n"," return 1\n"," return 0\n","\n","# i i-1 i-2 ... 2 1 0, keep these positions\n","def clear_bits_left_right(val, i):\n"," print('val', bin(val))\n"," mask = (1 << i) -1\n"," print('mask', bin(mask))\n"," return bin(val & (mask))\n","# i i-1 i-2 ... 2 1 0, erase these positions\n","def clear_bits_right_left(val, i):\n"," print('val', bin(val))\n"," mask = (1 << i) -1\n"," print('mask', bin(~mask))\n"," return bin(val & (~mask))\n","\n","\n","print(get_bit(5,1))\n","\n","print(clear_bits_left_right(int('11111111',2), 5))\n","print(clear_bits_right_left(int('11111111',2), 5))\n","\n","'''applications'''\n","def twos_complement(val, bits):\n"," # first flip implemented with xor of val with all 1's\n"," flip_val = val ^ (1 << bits - 1)\n"," #flip_val = ~val we only give 3 bits\n"," return bin(flip_val + 1)\n","\n","\n","def twos_complement2(val, bits):\n"," zeroFound = False\n"," ans = 0\n"," mask = 1\n"," for i in range(bits):\n"," b = (val & (mask)) # get ith bit\n"," print(b)\n"," b = not b # flipped\n"," if not zeroFound:\n"," if not b: # found zero, flip to one, else flip to zero: no operation needed\n"," print('found')\n"," ans = ans | (mask) # set ith bit\n"," zeroFound = True\n"," else:\n"," if b:\n"," ans = ans | (mask)\n"," mask = mask << 1 # change mask to the next bit\n"," return bin(ans)\n","\n","def twos_complement_result(x):\n"," ans1 = -x\n"," ans2 = ~x + 1\n"," print(ans1, ans2)\n"," print(bin(ans1), bin(ans2))\n"," return ans1\n","\n","def strip_last_set_bit(val):\n"," print(bin(val))\n"," return bin(val & (val - 1))\n","\n","def get_lowest_set_bit(val):\n"," return val ^ (val & (val -1))\n"," return (val & (-val))\n","\n","print(twos_complement(5, 8))\n","print(twos_complement2(5, 8))\n","print(strip_last_set_bit(5))\n","print(get_lowest_set_bit(8))\n","\n","twos_complement_result(8)"],"execution_count":0,"outputs":[]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/tree_data_structure.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"tree_data_structure.ipynb","version":"0.3.2","provenance":[],"toc_visible":true},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"3A2mprldYvXe","colab_type":"text"},"cell_type":"markdown","source":["### N-aray Tree"]},{"metadata":{"id":"h5LNx9p_ZxtH","colab_type":"text"},"cell_type":"markdown","source":["#### Define Tree Node"]},{"metadata":{"id":"9R_XYWC2Yz-G","colab_type":"code","colab":{}},"cell_type":"code","source":["class NaryNode:\n"," '''Define a n-ary node'''\n"," def __init__(self, n, val):\n"," self.children = [None] * n\n"," self.val = val\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"Xx5WEdJDZ4-q","colab_type":"text"},"cell_type":"markdown","source":["#### Define a Tree and implement operations"]},{"metadata":{"id":"qtAos_DOZwkw","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"wLPjQrfnZbQY","colab_type":"text"},"cell_type":"markdown","source":["### Binary Tree"]},{"metadata":{"id":"oUZYimKbZ1ZL","colab_type":"text"},"cell_type":"markdown","source":["#### Define Tree Node"]},{"metadata":{"id":"ZKknhNURZdA0","colab_type":"code","colab":{}},"cell_type":"code","source":["class BinaryNode:\n"," '''Define a classical binary tree node'''\n"," def __init__(self, val):\n"," self.left = None\n"," self.right = None\n"," self.val = val"],"execution_count":0,"outputs":[]},{"metadata":{"id":"yPukXXkXZ_zn","colab_type":"text"},"cell_type":"markdown","source":["#### Define a Tree and implement operations\n"," 1\n"," / \\ \n"," 2 3\n"," / \\ \\\n","4 5 6 "]},{"metadata":{"id":"CyXwZ9sf8dyG","colab_type":"code","colab":{}},"cell_type":"code","source":["root = BinaryNode(1)\n","left = BinaryNode(2)\n","right = BinaryNode(3)\n","root.left = left\n","root.right = right\n","left.left = BinaryNode(4)\n","left.right = BinaryNode(5)\n","right.right = BinaryNode(6)"],"execution_count":0,"outputs":[]},{"metadata":{"id":"gOHqKKfY_Ug0","colab_type":"code","colab":{}},"cell_type":"code","source":["def constructTree(a, idx):\n"," '''construct a binary tree recursively from input array a'''\n"," if idx >= len(a):\n"," return None\n"," node = BinaryNode(a[idx])\n"," node.left = constructTree(a, 2*idx + 1)\n"," node.right = constructTree(a, 2*idx + 2)\n"," return node"],"execution_count":0,"outputs":[]},{"metadata":{"id":"STvuN-5p_5Di","colab_type":"code","colab":{}},"cell_type":"code","source":["nums = [1, 2, 3, 4, 5, None, 6]\n","root = constructTree(nums, 0)"],"execution_count":0,"outputs":[]},{"metadata":{"id":"hrJC3v5ZAvD-","colab_type":"text"},"cell_type":"markdown","source":["#### To show the nodes at each level, we use LevelOrder function to print out the tree:"]},{"metadata":{"id":"uPxVdjRrA0UB","colab_type":"code","colab":{}},"cell_type":"code","source":["def LevelOrder(root):\n"," q = [root]\n"," while q:\n"," new_q = []\n"," for n in q:\n"," if n is not None:\n"," print(n.val, end=',')\n"," if n.left:\n"," new_q.append(n.left)\n"," if n.right:\n"," new_q.append(n.right)\n"," q = new_q\n"," print('\\n')\n"],"execution_count":0,"outputs":[]},{"metadata":{"id":"Pl2HGcHkA4rT","colab_type":"code","outputId":"2282a8ed-e1c1-4dae-b83c-0c2a8c19b470","executionInfo":{"status":"ok","timestamp":1550969967703,"user_tz":480,"elapsed":336,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":127}},"cell_type":"code","source":["LevelOrder(root)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["1,\n","\n","2,3,\n","\n","4,5,None,6,\n","\n"],"name":"stdout"}]},{"metadata":{"id":"2edkOHbCCV7n","colab_type":"text"},"cell_type":"markdown","source":[""]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/chapter_14_sorting_2.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"chapter_14_sorting.ipynb","version":"0.3.2","provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"B0qx9rvaser4","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"7c9daf13-4598-4e08-bc63-f6ab19c419da","executionInfo":{"status":"ok","timestamp":1549672814254,"user_tz":480,"elapsed":610,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["tup = (3, 6, 8, 2, 78, 1, 23, 45, 9)\n","sorted(tup)"],"execution_count":1,"outputs":[{"output_type":"execute_result","data":{"text/plain":["[1, 2, 3, 6, 8, 9, 23, 45, 78]"]},"metadata":{"tags":[]},"execution_count":1}]},{"metadata":{"id":"eA8dMPkksqly","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":71},"outputId":"613cc186-cd57-4439-9f7f-6b122cd3d85b","executionInfo":{"status":"ok","timestamp":1549673318708,"user_tz":480,"elapsed":276,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["from collections import defaultdict\n","import random\n","dic = defaultdict(lambda: defaultdict(list)) # a dictionary of a dictionary of list dic[a][b] = [3, 1, 2, 4]\n","for i in range(10):\n"," a = random.randint(1, 101)\n"," b = random.randint(1, 101)\n"," dic[a][b] = [random.randint(1, 101) for _ in range(10)]\n","print(dic) \n","sorted_dic = sorted(dic)\n","print(sorted_dic)"],"execution_count":8,"outputs":[{"output_type":"stream","text":["defaultdict( at 0x7faf20e3c730>, {72: defaultdict(, {59: [63, 15, 62, 83, 30, 98, 16, 44, 58, 93]}), 82: defaultdict(, {70: [89, 49, 47, 63, 90, 1, 7, 9, 78, 10]}), 53: defaultdict(, {62: [10, 99, 35, 78, 74, 44, 82, 32, 32, 52]}), 78: defaultdict(, {78: [20, 22, 100, 29, 16, 65, 56, 8, 100, 100]}), 13: defaultdict(, {44: [4, 81, 17, 92, 44, 49, 72, 24, 13, 64]}), 84: defaultdict(, {47: [76, 94, 36, 56, 60, 87, 72, 47, 75, 33]}), 49: defaultdict(, {97: [7, 47, 13, 80, 85, 59, 2, 48, 68, 65]}), 87: defaultdict(, {61: [31, 72, 71, 63, 19, 84, 78, 80, 97, 85]}), 17: defaultdict(, {92: [29, 53, 20, 14, 16, 84, 57, 40, 4, 19]}), 54: defaultdict(, {32: [2, 31, 19, 31, 68, 10, 85, 34, 25, 62]})})\n","[13, 17, 49, 53, 54, 72, 78, 82, 84, 87]\n"],"name":"stdout"}]},{"metadata":{"id":"VbmDX6yAvYax","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"441aa86e-17c6-4cbd-b923-67c1ea41e384","executionInfo":{"status":"ok","timestamp":1549674562513,"user_tz":480,"elapsed":273,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["'''sort_list_of_tuple()'''\n","\n","lst = [(1, 8, 2), (3, 2, 9), (1, 7, 10), (1, 7, 1), (11, 1, 5), (6, 3, 10), (32, 18, 9)]\n","sorted_lst = sorted(lst, key = lambda x: x[0]) # sort in the order of the first element, and descresing order of the second element, and incresing of the third element\n","print(sorted_lst)"],"execution_count":16,"outputs":[{"output_type":"stream","text":["[(1, 8, 2), (1, 7, 10), (1, 7, 1), (3, 2, 9), (6, 3, 10), (11, 1, 5), (32, 18, 9)]\n"],"name":"stdout"}]},{"metadata":{"id":"tXDvRwd_047E","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":34},"outputId":"231e3bd1-06df-4e6c-e4e8-ccfc7803ee62","executionInfo":{"status":"ok","timestamp":1549674993085,"user_tz":480,"elapsed":306,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["lst = [(1, 8, 2), (3, 2, 9), (1, 7, 10), (1, 7, 1), (11, 1, 5), (6, 3, 10), (32, 18, 9)]\n","sorted_lst = sorted(lst, key = lambda x: (x[0], -x[1], x[2])) # sort in the order of the first element, and descresing order of the second element, and incresing of the third element\n","print(sorted_lst)"],"execution_count":17,"outputs":[{"output_type":"stream","text":["[(1, 8, 2), (1, 7, 1), (1, 7, 10), (3, 2, 9), (6, 3, 10), (11, 1, 5), (32, 18, 9)]\n"],"name":"stdout"}]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/suffix_array.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"suffix_array.ipynb","version":"0.3.2","provenance":[],"toc_visible":true},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"3s7lvSxaj9Fi","colab_type":"text"},"cell_type":"markdown","source":["## sort cyclic shifts of string s + '$' to construct the suffix array"]},{"metadata":{"id":"JjYArMUrkDIu","colab_type":"code","colab":{}},"cell_type":"code","source":["from collections import OrderedDict\n","\n","def getCharOrder(s):\n"," n = len(s)\n"," numChars = 256\n"," count = [0]*numChars # totally 256 chars, if you want, can print it out to see these chars\n"," \n"," order = [0]*(n)\n"," \n"," #count the occurrence of each char\n"," for c in s:\n"," count[ord(c)] += 1\n"," \n"," # prefix sum of each char\n"," for i in range(1, numChars):\n"," count[i] += count[i-1]\n"," \n"," # assign from count down to be stable\n"," for i in range(n-1,-1,-1):\n"," count[ord(s[i])] -=1\n"," order[count[ord(s[i])]] = i # put the index into the order instead the suffix string\n"," \n"," return order\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"CXthy2Rqt6nm","colab_type":"code","colab":{}},"cell_type":"code","source":["def getCharClass(order, cls):\n"," n = len(order)\n"," cls = [0]*n\n"," # if it all differs, then cls[i] = order[i]\n"," cls[order[0]] = 0 #the 6th will be 0\n"," for i in range(1, n):\n"," # use order[i] as index, so the last index\n"," if s[order[i]] != s[order[i-1]]:\n"," print('diff',s[order[i]],s[order[i-1]])\n"," cls[order[i]] = cls[order[i-1]] + 1\n"," else:\n"," cls[order[i]] = cls[order[i-1]]\n"," return cls\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"yfCeF3b77m4M","colab_type":"code","colab":{}},"cell_type":"code","source":["'''It is a counting sort using the first part as class'''\n","def sortDoubled(s, L, order, cls):\n"," n = len(s)\n"," count = [0] * n\n"," new_order = [0] * n\n"," # their key is the class\n"," for i in range(n):\n"," count[cls[i]] += 1\n"," \n"," # prefix sum\n"," for i in range(1, n):\n"," count[i] += count[i-1]\n"," \n"," # assign from count down to be stable\n"," # sort the first half\n"," for i in range(n-1, -1, -1):\n"," start = (order[i] - L + n) % n #get the start index of the first half, \n"," count[cls[start]] -= 1\n"," new_order[count[cls[start]]] = start\n"," \n"," return new_order"],"execution_count":0,"outputs":[]},{"metadata":{"id":"2I1nIvImB3O8","colab_type":"code","colab":{}},"cell_type":"code","source":["def updateClass(order, cls, L):\n"," n = len(order)\n"," new_cls = [0]*n\n"," # if it all differs, then cls[i] = order[i]\n"," new_cls[order[0]] = 0 #the 6th will be 0\n"," for i in range(1, n):\n"," cur_order, prev_order = order[i], order[i-1]\n"," # use order[i] as index, so the last index\n"," if cls[cur_order] != cls[prev_order] or cls[(cur_order+L) % n] != cls[(prev_order+L) % n]:\n"," new_cls[cur_order] = new_cls[prev_order] + 1\n"," else:\n"," new_cls[cur_order] = new_cls[prev_order]\n"," return new_cls"],"execution_count":0,"outputs":[]},{"metadata":{"id":"2Wv3muUHkNl_","colab_type":"code","colab":{}},"cell_type":"code","source":["\n","def cyclic_shifts_sort(s):\n"," s = s + '$'\n"," n = len(s)\n"," order = getCharOrder(s)\n"," cls = getCharClass(s, order)\n"," print(order, cls)\n"," L = 1\n"," while L < n:\n"," order = sortDoubled(s, 1, order, cls)\n"," cls = updateClass(order, cls, L)\n"," print(order, cls)\n"," L *= 2\n"," \n"," return order"],"execution_count":0,"outputs":[]},{"metadata":{"id":"OpqYr3Z6rsM_","colab_type":"code","outputId":"eb382cee-6f8d-459c-911f-10c955b45dad","executionInfo":{"status":"ok","timestamp":1549232253713,"user_tz":480,"elapsed":336,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":146}},"cell_type":"code","source":["s = 'ababaa'\n","cyclic_shifts_sort(s)"],"execution_count":32,"outputs":[{"output_type":"stream","text":["diff a $\n","diff b a\n","[6, 0, 2, 4, 5, 1, 3] [1, 2, 1, 2, 1, 1, 0]\n","[6, 5, 4, 0, 2, 1, 3] [3, 4, 3, 4, 2, 1, 0]\n","[6, 5, 4, 0, 2, 3, 1] [3, 6, 4, 5, 2, 1, 0]\n","[6, 5, 4, 0, 2, 3, 1] [3, 6, 4, 5, 2, 1, 0]\n"],"name":"stdout"},{"output_type":"execute_result","data":{"text/plain":["[6, 5, 4, 0, 2, 3, 1]"]},"metadata":{"tags":[]},"execution_count":32}]},{"metadata":{"id":"5nNbGVRTjvvL","colab_type":"text"},"cell_type":"markdown","source":[""]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/chapter_8_heap_priority_queue.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"chapter_8_heap_priority_queue.ipynb","version":"0.3.2","provenance":[],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"XVLSsH816Oz9","colab_type":"text"},"cell_type":"markdown","source":["## Basic implementation"]},{"metadata":{"id":"RbAXuUtD6Swz","colab_type":"code","colab":{}},"cell_type":"code","source":["class Heap:\n"," def __init__(self):\n"," self.heap = [None]\n"," self.size = 0\n"," def __str__(self):\n"," out = ''\n"," for i in range(1, len(self.heap)):\n"," out += str(self.heap[i]) + ' '\n"," return out\n"," def _float(self, index): # enforce min-heap, leaf-to-root\n"," while index // 2: # while parent exist\n"," p_index = index // 2\n"," print('p', p_index, index)\n"," if self.heap[index] < self.heap[p_index]: # a violation\n"," # swap\n"," self.heap[index], self.heap[p_index] = self.heap[p_index], self.heap[index]\n"," else:\n"," break\n"," index = p_index # move up the node\n"," def insert(self, val):\n"," self.heap.append(val)\n"," self.size += 1\n"," self._float(index = self.size)\n"," \n"," def _sink(self, index): # enforce min-heap, root-to-leaf\n"," while 2 * index <= self.size:\n"," li = 2 * index\n"," ri = li + 1\n"," mi = index\n"," if self.heap[li] < self.heap[mi]:\n"," mi = li\n"," if ri <= self.size and self.heap[ri] < self.heap[mi]:\n"," mi = ri\n"," if mi != index:\n"," # swap index with mi\n"," self.heap[index], self.heap[mi] = self.heap[mi], self.heap[index]\n"," else:\n"," break\n"," index = mi\n"," def pop(self):\n"," val = self.heap[1]\n"," self.heap[1] = self. heap.pop()\n"," self.size -= 1\n"," self._sink(index = 1)\n"," return val\n"," \n"," def _float_till_root(self, index): # enforce min-heap, leaf-to-root\n"," while index // 2: # while parent exist\n"," p_index = index // 2\n"," print('p', p_index, index)\n"," if self.heap[index] < self.heap[p_index]: # a violation\n"," # swap\n"," self.heap[index], self.heap[p_index] = self.heap[p_index], self.heap[index]\n"," index = p_index # move up the node\n"," \n"," def heapify(self, lst):\n"," self.heap = [None] + lst\n"," self.size = len(lst)\n"," for i in range(self.size, self.size // 2, -1):\n"," print(self.heap[i])\n"," self._float_till_root(i)\n"," print('after', self.heap)\n"," \n"," def _sink_till_leaf(self, index): # enforce min-heap, root-to-leaf\n"," while 2 * index < self.size:\n"," li = 2 * index\n"," ri = li + 1\n"," mi = li if self.heap[li] < self.heap[ri] else ri\n"," if self.heap[index] > self.heap[mi]:\n"," # swap index with mi\n"," self.heap[index], self.heap[mi] = self.heap[mi], self.heap[index]\n"," index = mi\n"," \n"," def heapify_sink(self, lst):\n"," self.heap = [None] + lst\n"," self.size = len(lst)\n"," for i in range(self.size//2, 0, -1):\n"," self._sink(i)\n"," \n"," def heapsort(self, a):\n"," self.heapify_sink(a)\n"," n = len(a)\n"," for i in range(n, 1, -1): # position to put the root node\n"," self.heap[i], self.heap[1] = self.heap[1], self.heap[i] #swap root with i\n"," self.size -= 1\n"," self._sink(1) # sink dow the new root\n"," print(self.heap)\n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"5-FHH-6o6xPB","colab_type":"code","outputId":"ee4f66eb-affb-4277-c1f7-4895e073e45a","executionInfo":{"status":"ok","timestamp":1550521262381,"user_tz":480,"elapsed":336,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":311}},"cell_type":"code","source":["h = Heap()\n","lst = [21, 1, 45, 78, 3, 5]\n","for v in lst:\n"," h.insert(v)\n"," print(h)\n","print('heapify with insertion: ', h)\n","h.pop()\n","print('after pop(): ', h)\n","h.pop()\n","print(h)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["21 \n","p 1 2\n","1 21 \n","p 1 3\n","1 21 45 \n","p 2 4\n","1 21 45 78 \n","p 2 5\n","p 1 2\n","1 3 45 78 21 \n","p 3 6\n","p 1 3\n","1 3 5 78 21 45 \n","heapify with insertion: 1 3 5 78 21 45 \n","after pop(): 3 21 5 78 45 \n","5 21 45 78 \n"],"name":"stdout"}]},{"metadata":{"id":"WzVkLBxHMMKI","colab_type":"code","outputId":"4f89ad5a-fb4c-4cb8-c3d6-229a408fcccd","executionInfo":{"status":"ok","timestamp":1550534069698,"user_tz":480,"elapsed":924,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":139}},"cell_type":"code","source":["h = Heap()\n","lst = [21, 1, 45, 78, 3, 5]\n","h.heapify_sink(lst)\n","print('heapify with heapify:', h)"],"execution_count":14,"outputs":[{"output_type":"stream","text":["45\n","after [None, 21, 1, 5, 78, 3, 45]\n","1\n","after [None, 21, 1, 5, 78, 3, 45]\n","21\n","after [None, 1, 3, 5, 78, 21, 45]\n","heapify with heapify: 1 3 5 78 21 45 \n"],"name":"stdout"}]},{"metadata":{"id":"TgA1qpeyarvs","colab_type":"code","outputId":"27a2fd8a-a52b-4867-d3fa-5efab881f033","executionInfo":{"status":"ok","timestamp":1550524082582,"user_tz":480,"elapsed":337,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":237}},"cell_type":"code","source":["h = Heap()\n","h.heapsort(lst)\n","print(h)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["45\n","after [None, 21, 1, 45, 78, 3, 5]\n","1\n","after [None, 21, 1, 45, 78, 3, 5]\n","21\n","after [None, 1, 3, 45, 78, 21, 5]\n","[None, 3, 5, 45, 78, 21, 1]\n","[None, 5, 21, 45, 78, 3, 1]\n","[None, 21, 78, 45, 5, 3, 1]\n","[None, 45, 78, 21, 5, 3, 1]\n","[None, 78, 45, 21, 5, 3, 1]\n","78 45 21 5 3 1 \n"],"name":"stdout"}]},{"metadata":{"id":"tTDxuoKlcyzD","colab_type":"text"},"cell_type":"markdown","source":["### through heapq"]},{"metadata":{"id":"x0oarRTYc1fH","colab_type":"code","colab":{}},"cell_type":"code","source":["from heapq import heapify, heappop\n","def heapsort(a):\n"," heapify(a)\n"," return [heappop(a) for i in range(len(a))]\n"],"execution_count":0,"outputs":[]},{"metadata":{"id":"A4yuYo2Hc8Ny","colab_type":"code","outputId":"702ef55b-c9a0-4dd6-91cc-c0d81e6a9b1d","executionInfo":{"status":"ok","timestamp":1550525084329,"user_tz":480,"elapsed":381,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["lst = [21, 1, 45, 78, 3, 5]\n","heapsort(lst)"],"execution_count":0,"outputs":[{"output_type":"execute_result","data":{"text/plain":["[1, 3, 5, 21, 45, 78]"]},"metadata":{"tags":[]},"execution_count":74}]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/chapter_6_linear_data_structure.depre.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"chapter_6_linear_data_structure.ipynb","version":"0.3.2","provenance":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"3i76tIL3-e9f","colab_type":"code","colab":{}},"cell_type":"code","source":["class Student:\n"," def __init__(self, name, grade, age):\n"," self.name = name\n"," self.grade = grade\n"," self.age = age\n"," def __repr__(self):\n"," return repr((self.name, self.grade, self.age))\n"," \n"," def __cmp__(self, other):\n"," return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age))\n","# def __hash__(self):\n","# return hash((self.name, self.grade, self.age))\n"," \n","# def __lt__(self, other):\n","# return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age)) < 0\n","# def __gt__(self, other):\n","# return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age)) > 0\n","# def __eq__(self, other):\n","# return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age)) == 0\n","# def __le__(self, other):\n","# return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age)) <= 0\n","# def __ge__(self, other):\n","# return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age)) >= 0\n","# def __ne__(self, other):\n","# return cmp((self.name, self.grade, self.age), (other.name, other.grade, other.age)) != 0"],"execution_count":0,"outputs":[]},{"metadata":{"id":"D7cql5y2_DYq","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":72},"outputId":"0af43264-6e4a-4d7a-e5b8-70eb7b71daa9","executionInfo":{"status":"ok","timestamp":1549751870866,"user_tz":480,"elapsed":300,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["a =Student('John', 'A', 14)\n","print(type(('John', 'A', 14)), type(a))\n","print(hash(a))\n","print(a)"],"execution_count":58,"outputs":[{"output_type":"stream","text":[" \n","-9223363270192343580\n","('John', 'A', 14)\n"],"name":"stdout"}]},{"metadata":{"id":"9WTYRI2yNA4G","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":338},"outputId":"613e4070-7e98-4da7-e9ad-bffec3f9121c","executionInfo":{"status":"error","timestamp":1549749345765,"user_tz":480,"elapsed":334,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["b = Student('Alex', 'A', 14)\n","print(a == b)\n","print(sorted([a,b]))"],"execution_count":56,"outputs":[{"output_type":"error","ename":"NameError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mStudent\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Alex'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'A'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m14\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msorted\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m\u001b[0m in \u001b[0;36m__eq__\u001b[0;34m(self, other)\u001b[0m\n\u001b[1;32m 17\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mcmp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgrade\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgrade\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 18\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m__eq__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 19\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mcmp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgrade\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgrade\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 20\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m__le__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mcmp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgrade\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgrade\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mother\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mNameError\u001b[0m: name 'cmp' is not defined"]}]},{"metadata":{"id":"ylfCmcuAaTEA","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":227},"outputId":"29974383-bd6e-427d-94d9-0141947e36c8","executionInfo":{"status":"error","timestamp":1549752233299,"user_tz":480,"elapsed":333,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["key1 = hash(('John', 'A', 14))\n","key2 = hash(('John', 'A', 14))\n","print(key1, key2)\n","d = {('John', 'A', 14): 'A+'}\n","print(d[key1], d['John', 'A', 14])"],"execution_count":77,"outputs":[{"output_type":"stream","text":["1266846023488010213 1266846023488010213\n"],"name":"stdout"},{"output_type":"error","ename":"KeyError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)","\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mkey2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0md\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'John'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'A'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m14\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'A+'\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mkey1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'John'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'A'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m14\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mKeyError\u001b[0m: 1266846023488010213"]}]}]} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # *Hands-on Algorithmic Problem Solving* 2 | ### *Creates Passion and Confidence from Mastering Algorithmic Problem Solving and Problem Patterns of Real Interview Questions* 3 | 4 | 5 | 6 | 7 | [![alt text][3.1]][3] 8 | [![alt text][1.1]][1] 9 | [![alt text][2.1]][2] 10 | [![Medium Blog][4.1]][4] 11 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | [1.1]: http://i.imgur.com/tXSoThF.png (twitter icon with padding) 21 | [2.1]: http://i.imgur.com/P3YfQoD.png (facebook icon with padding) 22 | [3.1]: https://www.iconfinder.com/icons/2329259/download/png/32 (google plus icon with padding) 23 | [4.1]: https://img.icons8.com/ios-filled/28/000000/medium-monogram.png 24 | 25 | 27 | 28 | 29 | 30 | [1.2]: http://i.imgur.com/wWzX9uB.png (twitter icon without padding) 31 | [2.2]: http://i.imgur.com/fep1WsG.png (facebook icon without padding) 32 | [3.2]: http://i.imgur.com/VlgBKQ9.png (google plus icon without padding) 33 | [4.2]: http://i.imgur.com/jDRp47c.png (tumblr icon without padding) 34 | [5.2]: http://i.imgur.com/Vvy3Kru.png (dribbble icon without padding) 35 | [6.2]: http://i.imgur.com/9I6NRUm.png (github icon without padding) 36 | 37 | 38 | 39 | 40 | 41 | [1]: https://twitter.com/liyinscience 42 | [2]: https://www.facebook.com/li.yin.355 43 | [3]: https://www.linkedin.com/in/li-yin-00b0456b/ 44 | [4]: https://medium.com/algorithms-and-leetcode 45 | [5]: http://dribbble.com/carlsednaoui 46 | [6]: http://www.github.com/carlsednaoui 47 | 48 | 49 | 50 | ## Purpose 51 | The purpose of the book is to guide the reader's preparation to crack the coding interviews. Preparing for the coding interview, not easy! Cracking the coding interivew? Like impossible for most of us! Luck does play a slight role sometimes in the outcome. So, just treating it as a learning process. No matter what the result is, there will be no regret. 52 | 53 | Computer Science is really not just computer science. It is a combination of all fields; our normal interview problems fall into the eumerative combinatorics and our computer vision mostly is related to Linear Algebra. What really matters is our passion about learning more and applying it to solve real-life problems. How about forgetting about cracking the coding interviews, and just simply enjoy a ride that trying to seek the `soul` of the programming world. I'm just like you, I love to learn and I love to write and try to do a better job. No matter how much time it takes, because I love learning it! 54 | 55 | There are plenty of books out there focusing on either teaching algorithmic knowledge (*Introduction to Algorithms*, *Algorithmic Problem Solving*, etc) or introducing interview process and solving interview problems(*Cracking the Coding Interview*--seriously, you are not likely to crack any interviews with this book, haha!, *Coding Interview Questions*, etc), but barely any that combines the two. This is a book designed to make up this role in the categorization; learning the algorithmic problem solving by analyzing and practicing interview problems -- a reciprocal relationship that makes 1+1=4: Algorithms, Interviews, Passion, and Confidence. 56 | 57 | 58 | 59 | This is **NOT** a book that provides hiring statistic of each company or gives the reader quick tricks in order to pass a few coding interviews(T'm not good with NLP, 'cause I'm a computer vision person). Its purpose is to show you the beauty of the algorithimc problem solving in the hope that you will be more passionate and condifent about software engineering; the interview questions just set up a play ground where we strengthen what we learn. A strong candidate would be apt to sleep well before interviews, walk into the interviews and discuss his or her findings about the question from all possible angles and program the best solution for on the white-board. The interviews shall be a setting the interviewers and interviewees both have a nice and happy talk; learning from each other instead of a one-way relation -- tester and testee. 60 | 61 | 63 | 64 | ## Content Format 65 | Related content will be posted in the form of [medium publication](https://medium.com/algorithms-and-leetcode) and as a book in pdf instead of directly using markdown for better visual appearance and organization. 66 | 67 | ## Table of Contents 68 | 69 | 70 | ### Warm Up: Abstract Data Structures and Tools 71 | * [Abstract Data Structures](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/Abstract%20Data%20Structures.pdf) 72 | * Discrete Programming 73 | * Recurrence Relation 74 | 75 | ### Get Started: Programming and Python Data Structures 76 | * Iteration and Recursion 77 | * Bit Manipulation 78 | * **Python Data Structures** 79 | > * [PDF](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/Python%20Data%20Structure.pdf) 80 | > * [source code](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_python_datastrcutures.ipynb) 81 | 82 | ### Core Principles: Algorithm Design and Analysis 83 | * Complexity Analysis 84 | * Search Strategies 85 | > * [PDF](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/search_strategies.pdf) 86 | > * [source code: Graph Search](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_search_strategies.ipynb) 87 | > * [source code: Tree Traversal](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_tree_data_structure_and_traversal.ipynb) 88 | * Combinatorial Search 89 | > * [PDF](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/combinatorial_search.pdf) 90 | > * [source code](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_combinatorial_search.ipynb) 91 | * Reduce and Conquer 92 | * **Decrease and Conquer** 93 | > * [Binary Search, Binary Search Tree, and Segment Tree](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/decrease_and_conquer.pdf) 94 | > * [source code](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_decrease_and_conquer.ipynb) 95 | * **Sorting and Selection** 96 | > * [PDF](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/sorting_algorithms_with_python3.pdf) 97 | > * [source code: sorting algorithms](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_sorting_and_selection_algorithms.ipynb) 98 | > * [source code: Python comparison and sort functions](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/chapter_python_comparison_sorting.ipynb) 99 | * Dynamic Programming 100 | * Greedy Algorithms 101 | 102 | ### Classical Algorithms 103 | * **Advanced Search on Linear Data Structures** 104 | > * [PDF](https://github.com/liyin2015/Algorithms-and-Coding-Interviews/blob/master/advanced_search_on_linear_data_structures.pdf) 105 | > * [source code](https://nbviewer.jupyter.org/github/liyin2015/Algorithms-and-Coding-Interviews/blob/master/Advanced_Search_on_Linear_Data_Structures.ipynb) 106 | * Advanced Graph Algorithms 107 | * Advanced Data Structures 108 | * String Pattern Matches 109 | * Math and Geometry Algorithms 110 | 111 | ### Problem Patterns 112 | * Dynamic Programming Questions (15%) 113 | * Array Questions (15%) 114 | * Linked List, Stack, Queue, and Heap Questions (12%) 115 | * String Questions (15%) 116 | * Tree Questions (10%) 117 | * Graph Questions (15%) 118 | 119 | 137 | 138 | *Note: everything is still in progress, so use it with caution.* 139 | 140 | ## Referring Books and Materials 141 | 142 | * Skiena, Steven S. The algorithm design manual: Text. Vol. 1. Springer Science & Business Media, 1998. 143 | 144 | * T. H. Cormen, Introduction to algorithms, MIT press, 2009. 145 | 146 | * Manber, Udi. Introduction to algorithms: a creative approach. Addison-Wesley Longman Publishing Co., Inc., 1989. 147 | 148 | * Kleinberg, Jon, and Eva Tardos. Algorithm design. Pearson Education India, 2006. 149 | 150 | * Russell, Stuart J., and Peter Norvig. Artificial intelligence: a modern approach. Malaysia; Pearson Education Limited,, 2016. (**Best book ever in explaining searching problem-solving, differentiate tree-search and graph-search**) 151 | 152 | * D. M. Beazley, Python essential reference, Addison-Wesley Professional,2009. 153 | 154 | * S. Halim and F. Halim, Competitive Programming 3, Lulu Independent 155 | Publish, 2013. 156 | 157 | * B. Slatkin, Effective Python: 59 Specific Ways to Write Better Python,Pearson Education, 2015. 158 | 159 | * H. hua jiang, “Leetcode blogs,” https://zxi.mytechroad.com/blog/category, 2018, [Online; accessed 19-July-2018]. 160 | 161 | * B. Baka, “Python data structures and algorithms: Improve application performance with graphs, stacks, and queues,” 2017. 162 | 163 | * “Competitive Programming,”https://cp-algorithms.com/, 2019, [Online; accessed 19-July-2018]. 164 | 165 | * “cs princeton,”https://aofa.cs.princeton.edu/60trees/, 2019, 166 | [Online; accessed 19-July-2018] 167 | 168 | ## Tools 169 | * Graph Visualize with [graphviz](http://www.webgraphviz.com/). [Examples](https://graphs.grevian.org/example). [Tutorial to use Python](https://graphviz.readthedocs.io/en/stable/manual.html) 170 | 171 | ## Mocking Interviews 172 | Practice is important. Schedule some mocking interviews with [interviewing.io](https://interviewing.io/) 173 | 174 | 175 | 176 | ## Feedback 177 | If you have ideas to improve the book, about formatting, more contents, or correct the errors, do not hesitate to let me know. 178 | 179 | 181 | -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/graph_search_application.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"graph_search_application.ipynb","version":"0.3.2","provenance":[],"toc_visible":true},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"auwghE4hWHSK","colab_type":"text"},"cell_type":"markdown","source":["### Cycle Check"]},{"metadata":{"id":"6nYEnOCo3FOC","colab_type":"code","colab":{}},"cell_type":"code","source":["# initialization\n","class STATE:\n"," white = 0\n"," gray = 1\n"," black = 2"],"execution_count":0,"outputs":[]},{"metadata":{"id":"dLTp6RWw2mYX","colab_type":"text"},"cell_type":"markdown","source":["### For directed graph"]},{"metadata":{"id":"xPzr88zz2pw_","colab_type":"code","outputId":"3bd3c586-7da2-420e-c60c-d24569711308","executionInfo":{"status":"ok","timestamp":1552244194011,"user_tz":420,"elapsed":539,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["al = [[] for _ in range(7)]\n","\n","# set 8 edges\n","al[0] = [1]\n","al[1] = [2]\n","al[2] = [0, 4]\n","al[4] = [3]\n","al[5] = [6]\n","\n","print(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1], [2], [0, 4], [], [3], [6], []]\n"],"name":"stdout"}]},{"metadata":{"id":"iq07bZAp29mi","colab_type":"code","colab":{}},"cell_type":"code","source":["def hasCycle(g, s, state):\n"," '''convert dfs to check cycle'''\n"," state[s] = STATE.gray # first be visited\n"," for v in g[s]:\n"," if state[v] == STATE.white:\n"," if hasCycle(g, v, state):\n"," return True\n"," elif state[v] == STATE.gray: # aback edge\n"," return True\n"," else:\n"," pass\n"," state[s] = STATE.black # mark it as complete\n","\n"," return False\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"zbtKB8Rg3bWg","colab_type":"code","colab":{}},"cell_type":"code","source":["def cycleDetect(g):\n"," '''cycle detect in directed graph'''\n"," n = len(g)\n"," state = [STATE.white] * n\n"," for i in range(n):\n"," if state[i] == STATE.white:\n"," if hasCycle(g, i, state):\n"," print('cycle starts at vertex ', i)\n"," return True\n"," return False"],"execution_count":0,"outputs":[]},{"metadata":{"id":"q-0e10OJ4M5i","colab_type":"code","outputId":"54d8c30c-f873-4ed4-84c4-ff1e3e2fdc7a","executionInfo":{"status":"ok","timestamp":1552244246348,"user_tz":420,"elapsed":338,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["cycleDetect(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["cycle starts at vertex 5\n"],"name":"stdout"},{"output_type":"execute_result","data":{"text/plain":["True"]},"metadata":{"tags":[]},"execution_count":6}]},{"metadata":{"id":"GTx9ANEY562r","colab_type":"text"},"cell_type":"markdown","source":["#### For undirected Graph"]},{"metadata":{"id":"wE01rAq55-oF","colab_type":"code","colab":{}},"cell_type":"code","source":["def hasCycle(g, s, p, state):\n"," '''convert dfs to check cycle'''\n"," state[s] = STATE.gray # first be visited\n"," for v in g[s]:\n"," if state[v] == STATE.white:\n"," if hasCycle(g, v, s, state):\n"," return True\n"," elif state[v] == STATE.gray and v != p: # aback edge\n"," return True\n"," else:\n"," pass\n"," state[s] = STATE.black # mark it as complete\n","\n"," return False"],"execution_count":0,"outputs":[]},{"metadata":{"id":"sA6dMqrE7MOC","colab_type":"code","colab":{}},"cell_type":"code","source":["def cycleDetect(g):\n"," '''cycle detect in directed graph'''\n"," n = len(g)\n"," state = [STATE.white] * n\n"," for i in range(n):\n"," if state[i] == STATE.white:\n"," if hasCycle(g, i, -1, state):\n"," print('cycle starts at vertex ', i)\n"," return True\n"," return False"],"execution_count":0,"outputs":[]},{"metadata":{"id":"aD-FizTB6WbB","colab_type":"code","outputId":"6bc3e3f4-bcfa-443d-e037-49ca81fca9d7","executionInfo":{"status":"ok","timestamp":1552244252680,"user_tz":420,"elapsed":592,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["al = [[] for _ in range(7)]\n","\n","# set 8 edges\n","al[0] = [1, 2]\n","al[1] = [0, 2]\n","al[2] = [0, 4]\n","al[4] = [2, 3]\n","al[5] = [6]\n","al[6] = [5]\n","\n","print(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1, 2], [0, 2], [0, 4], [], [2, 3], [6], [5]]\n"],"name":"stdout"}]},{"metadata":{"id":"30NtiTxy7TIq","colab_type":"code","outputId":"d1c19bb1-7043-469c-a8f3-a40a800abaa3","executionInfo":{"status":"ok","timestamp":1552244255134,"user_tz":420,"elapsed":563,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["cycleDetect(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["cycle starts at vertex 0\n"],"name":"stdout"},{"output_type":"execute_result","data":{"text/plain":["True"]},"metadata":{"tags":[]},"execution_count":10}]},{"metadata":{"id":"WkpyVhW8WMN1","colab_type":"text"},"cell_type":"markdown","source":["### Topolgical Sort"]},{"metadata":{"id":"G1MfbU4eWPrA","colab_type":"code","outputId":"f615d164-63d1-4533-95db-4413433655d4","executionInfo":{"status":"ok","timestamp":1552244256915,"user_tz":420,"elapsed":510,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["al = [[] for _ in range(7)]\n","\n","# set 8 edges\n","al[0] = [1]\n","al[1] = [2]\n","al[2] = [4]\n","al[3] = []\n","al[4] = [3, 5]\n","al[5] = [6]\n","al[6] = []\n","\n","print(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1], [2], [4], [], [3, 5], [6], []]\n"],"name":"stdout"}]},{"metadata":{"id":"Pf7Jaj8CXWSM","colab_type":"code","colab":{}},"cell_type":"code","source":["def dfs(g, s, colors, orders, complete_orders):\n"," colors[s] = STATE.gray\n"," orders.append(s)\n"," for v in g[s]:\n"," if colors[v] == STATE.white:\n"," dfs(g, v, colors, orders, complete_orders)\n"," # complete\n"," colors[s] = STATE.black # this is not necessary in the code, just to help track the state\n"," complete_orders.append(s)\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"FvKHA5plXaoW","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]},{"metadata":{"id":"hbTw8Pf3YzjJ","colab_type":"code","colab":{}},"cell_type":"code","source":["def topo_sort(g):\n"," n = len(g)\n"," orders, complete_orders = [], []\n"," colors = [STATE.white] * n\n"," for i in range(n): # run dfs on all the node\n"," if colors[i] == STATE.white:\n"," dfs(g,i, colors, orders, complete_orders)\n","\n"," #print(orders, complete_orders[::-1])\n"," return orders, complete_orders[::-1]"],"execution_count":0,"outputs":[]},{"metadata":{"id":"WeoxmZkcZUKA","colab_type":"code","outputId":"961ef42a-ee79-4d5c-d8a5-bcc71ecf495c","executionInfo":{"status":"ok","timestamp":1552244278240,"user_tz":420,"elapsed":360,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["orders, complete_orders = topo_sort(al)\n","print(orders, complete_orders)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[0, 1, 2, 4, 3, 5, 6] [0, 1, 2, 4, 5, 6, 3]\n"],"name":"stdout"}]},{"metadata":{"id":"nHK_jknJXrhq","colab_type":"text"},"cell_type":"markdown","source":["Now, change the edge (2->4) to (4->2) and run the code again."]},{"metadata":{"id":"TX9opC9CXqbZ","colab_type":"code","outputId":"caa8397f-c251-4f8e-c469-7399412eec16","executionInfo":{"status":"ok","timestamp":1552244281902,"user_tz":420,"elapsed":392,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["al[2].remove(4)\n","al[4].append(2)\n","print(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1], [2], [], [], [3, 5, 2], [6], []]\n"],"name":"stdout"}]},{"metadata":{"id":"AXgDs24MYJHA","colab_type":"code","outputId":"881cb099-d2d1-4f6e-a8d7-e0c08c5d9108","executionInfo":{"status":"ok","timestamp":1552244283447,"user_tz":420,"elapsed":405,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["orders, complete_orders = topo_sort(al)\n","print(orders, complete_orders)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[0, 1, 2, 3, 4, 5, 6] [4, 5, 6, 3, 0, 1, 2]\n"],"name":"stdout"}]},{"metadata":{"id":"GTwh1v4l7G2B","colab_type":"text"},"cell_type":"markdown","source":["### Connected Components\n","\n","In the example, we only experiment with BFS. "]},{"metadata":{"id":"kIPfcNX9ARU7","colab_type":"code","colab":{}},"cell_type":"code","source":["def bfs(g, s, state):\n"," state[s] = True\n"," \n"," q, orders = [s], [s]\n"," while q:\n"," u = q.pop(0)\n"," \n"," for v in g[u]:\n"," if not state[v]:\n"," state[v] = True\n"," q.append(v)\n"," orders.append(v)\n"," return orders"],"execution_count":0,"outputs":[]},{"metadata":{"id":"eH7-zUmhAoDp","colab_type":"code","colab":{}},"cell_type":"code","source":["def connectedComponent(g):\n"," n = len(g)\n"," ccs = []\n"," state = [False] * n\n"," for i in range(n):\n"," if not state[i]:\n"," ccs.append(bfs(g, i, state))\n"," return ccs \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"6VWvKNSGBLeA","colab_type":"code","outputId":"8df73569-85f6-4b11-a59a-66ea47411c6d","executionInfo":{"status":"ok","timestamp":1552244289362,"user_tz":420,"elapsed":371,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["al = [[] for _ in range(7)]\n","\n","# set 8 edges\n","al[0] = [1, 2]\n","al[1] = [0, 2]\n","al[2] = [0, 4]\n","al[4] = [2, 3]\n","al[5] = [6]\n","al[6] = [5]\n","\n","print(al)\n","print(connectedComponent(al))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1, 2], [0, 2], [0, 4], [], [2, 3], [6], [5]]\n","[[0, 1, 2, 4, 3], [5, 6]]\n"],"name":"stdout"}]},{"metadata":{"id":"arzllBW_GsIX","colab_type":"text"},"cell_type":"markdown","source":["####Strongly connected components"]},{"metadata":{"id":"WkIxpFk7GvkW","colab_type":"code","outputId":"589d3781-35f5-45e4-cbe1-65446ddb50ba","executionInfo":{"status":"ok","timestamp":1552244293701,"user_tz":420,"elapsed":360,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["'''in the second undirected graph'''\n","al2 = [[] for _ in range(7)]\n","\n","# set 8 edges\n","al2[0] = [1]\n","al2[1] = [2]\n","al2[2] = [0, 4]\n","al2[4] = [3]\n","al2[5] = [6]\n","\n","print(al)\n","\n","'''in the first undirected graph'''\n","al1 = al2[::]\n","\n","al1[3].append(1)\n","\n","print(al1)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1, 2], [0, 2], [0, 4], [], [2, 3], [6], [5]]\n","[[1], [2], [0, 4], [1], [3], [6], []]\n"],"name":"stdout"}]},{"metadata":{"id":"0c7CQ8aUIw1c","colab_type":"code","colab":{}},"cell_type":"code","source":["def topo_sort(g):\n"," v = len(al)\n"," orders, complete_orders = [], []\n"," colors = [STATE.white] * v\n"," for i in range(v): # run dfs on all the node\n"," if colors[i] == STATE.white:\n"," dfs(al,i, colors, orders, complete_orders)\n"," return complete_orders[::-1]"],"execution_count":0,"outputs":[]},{"metadata":{"id":"H3ra08cvIz5B","colab_type":"code","outputId":"41e31576-c092-4f7a-919b-1cb22d1eda04","executionInfo":{"status":"ok","timestamp":1552244300038,"user_tz":420,"elapsed":326,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["print(topo_sort(al2))\n","print(topo_sort(al1))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[5, 6, 0, 1, 2, 4, 3]\n","[5, 6, 0, 1, 2, 4, 3]\n"],"name":"stdout"}]},{"metadata":{"id":"YVz-BG3YFJFX","colab_type":"text"},"cell_type":"markdown","source":["### Minimum Spanning Tree"]},{"metadata":{"id":"tI9aTeoy7Z2p","colab_type":"text"},"cell_type":"markdown","source":["#### Prim's Algorithm"]},{"metadata":{"id":"ZUW60VFQGwiD","colab_type":"code","colab":{}},"cell_type":"code","source":["a= {1:[(2, 2), (3, 12), (4, 10)], 2:[(1, 2), (3, 8), (5, 9)], 3:[(1, 12), (2, 8), (4, 6), (5, 3)], 4:[(1, 10),(3, 6), (5, 7)], 5:[(2, 9), (3, 3), (4, 7)]}\n","\n","class edge():\n"," def __init__(self, pid, id, w ):\n"," self.pid = pid\n"," self.id = id\n"," self.w = w\n"," def __lt__(self, other):\n"," return self.w < other.w\n"," \n"," def __eq__(self, other):\n"," return self.w == other.w\n"," \n"," def __str__(self):\n"," return str(self.pid) + '->' + str(self.id) + ':' + str(self.w)\n"," \n"],"execution_count":0,"outputs":[]},{"metadata":{"id":"AdLTUkgxAI1I","colab_type":"code","colab":{}},"cell_type":"code","source":["import queue\n","def prim(g, n):\n"," # step 1:\n"," start = 1\n"," V = {start} #spanning tree set\n"," E = queue.PriorityQueue() # the set of all edges, \n"," ans = []\n"," \n"," while len(V) < n:\n"," # add edges of start, and the other endpoint is in nv\n"," idlst = g[start]\n"," for id, w in idlst:\n"," if id not in V:\n"," E.put(edge(start, id, w))\n"," \n"," while E:\n"," # pick the smallest edge\n"," minEdge = E.get()\n","\n"," if minEdge.id not in V:\n"," # set the new id as start\n"," start = minEdge.id\n"," # add this id to the set of tree nodes\n"," V.add(minEdge.id)\n"," ans.append(minEdge)\n"," break\n"," return ans\n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"40vRdighTR8f","colab_type":"code","outputId":"d3c8197f-536b-4868-8f21-6dab330cdf69","executionInfo":{"status":"ok","timestamp":1553243555679,"user_tz":420,"elapsed":802,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":90}},"cell_type":"code","source":["ans = prim(a, 5)\n","for e in ans:\n"," print(e)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["1->2:2\n","2->3:8\n","3->5:3\n","3->4:6\n"],"name":"stdout"}]},{"metadata":{"id":"0r0DIbiU7d_v","colab_type":"code","colab":{}},"cell_type":"code","source":["class node:\n"," def __init__(self, p, w):\n"," self.p = p\n"," self.w = w\n"," def __lt__(self, other):\n"," return self.w < other.w\n"," def __eq__(self, other):\n"," return self.w == other.w\n"," def __str__(self):\n"," return str(self.p) + '->' +str(self.id)+':'+str(self.w)\n","\n"],"execution_count":0,"outputs":[]},{"metadata":{"id":"iE1wCIcbtj7t","colab_type":"code","colab":{}},"cell_type":"code","source":["def extractMin(q):\n"," minNode = None\n"," minW = float('inf')\n"," minIndex = -1\n"," for idx, node in enumerate(q):\n"," if node.w < minW:\n"," minNode = node\n"," minW = node.w\n"," minIdx = idx\n"," #q.remove(minNode)\n"," return minNode, minIdx\n","\n","def primMst(g, n):\n"," q = [None]*n\n"," S = {}\n"," ans = []\n"," for i in range(n):\n"," q[i] = node(None, float('inf'))\n"," q[0] = node(None, 0)\n"," S = {1}\n"," # main process\n"," while len(S) < n:\n"," minNode, minIdx = extractMin(q)\n"," S.add(minIdx+1)\n"," if minNode.p is not None:\n"," ans.append((minNode.p+1, minIdx+1))\n"," q[minIdx] = node(None, float('inf'))\n"," for v, w in g[minIdx+1]:\n"," if v not in S and w < q[v-1].w:\n"," q[v-1].p = minIdx\n"," q[v-1].w = w\n"," return ans\n"," \n"," \n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"JzWJqXcYRuyh","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":35},"outputId":"c71f7b89-d6f5-40d5-cc45-f8391f4511b9","executionInfo":{"status":"ok","timestamp":1553382526262,"user_tz":420,"elapsed":401,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["print(primMst(a, 5))"],"execution_count":42,"outputs":[{"output_type":"stream","text":["[(1, 2), (2, 3), (3, 5), (3, 4)]\n"],"name":"stdout"}]},{"metadata":{"id":"vwa3SlexCQAn","colab_type":"text"},"cell_type":"markdown","source":["#### Kruskal's Algorithm"]},{"metadata":{"id":"QC19-o-XCUF1","colab_type":"code","colab":{}},"cell_type":"code","source":["def kruskalMst(g, n):"],"execution_count":0,"outputs":[]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/graph_search.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"graph_search.ipynb","version":"0.3.2","provenance":[],"collapsed_sections":[],"toc_visible":true},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"ZhL7pFlp8gTD","colab_type":"text"},"cell_type":"markdown","source":["## Backtracking\n","\n","1. Permutation\n","2. Combination\n","3. All Paths\n","\n","\n","\n"]},{"metadata":{"id":"a76_VshDTaE4","colab_type":"text"},"cell_type":"markdown","source":["### Permutation"]},{"metadata":{"id":"XhTLVA0sZw61","colab_type":"code","colab":{}},"cell_type":"code","source":["def A_n_k(a, n, k, depth, used, curr, ans):\n"," '''\n"," Implement permutation of k items out of n items\n"," depth: start from 0, and represent the depth of the search\n"," used: track what items are in the partial solution from the set of n\n"," curr: the current partial solution\n"," ans: collect all the valide solutions\n"," '''\n"," if depth == k: #end condition\n"," ans.append(curr[::]) # use deepcopy because curr is tracking all partial solution, it eventually become []\n"," return\n"," \n"," for i in range(n):\n"," if not used[i]:\n"," # generate the next solution from curr\n"," curr.append(a[i])\n"," used[i] = True\n"," print(curr)\n"," # move to the next solution\n"," A_n_k(a, n, k, depth+1, used, curr, ans)\n"," \n"," #backtrack to previous partial state\n"," curr.pop()\n"," print('backtrack: ', curr)\n"," used[i] = False\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"RVZsfQb9_Xga","colab_type":"code","outputId":"bb9e8b92-0d8e-4cb7-8dd9-06f2c3384151","executionInfo":{"status":"ok","timestamp":1553585906154,"user_tz":420,"elapsed":440,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":555}},"cell_type":"code","source":["a = [1, 2, 3]\n","n = len(a)\n","ans = [[None]]\n","used = [False] * len(a)\n","ans = []\n","A_n_k(a, n, n, 0, used, [], ans)\n","print(ans)\n"],"execution_count":4,"outputs":[{"output_type":"stream","text":["[1]\n","[1, 2]\n","[1, 2, 3]\n","backtrack: [1, 2]\n","backtrack: [1]\n","[1, 3]\n","[1, 3, 2]\n","backtrack: [1, 3]\n","backtrack: [1]\n","backtrack: []\n","[2]\n","[2, 1]\n","[2, 1, 3]\n","backtrack: [2, 1]\n","backtrack: [2]\n","[2, 3]\n","[2, 3, 1]\n","backtrack: [2, 3]\n","backtrack: [2]\n","backtrack: []\n","[3]\n","[3, 1]\n","[3, 1, 2]\n","backtrack: [3, 1]\n","backtrack: [3]\n","[3, 2]\n","[3, 2, 1]\n","backtrack: [3, 2]\n","backtrack: [3]\n","backtrack: []\n","[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n"],"name":"stdout"}]},{"metadata":{"id":"HikETMOQcM7H","colab_type":"text"},"cell_type":"markdown","source":["### Combination"]},{"metadata":{"id":"fcIaL7i7-9na","colab_type":"code","colab":{}},"cell_type":"code","source":["def C_n_k(a, n, k, start, depth, curr, ans):\n"," '''\n"," Implement combination of k items out of n items\n"," start: the start of candinate\n"," depth: start from 0, and represent the depth of the search\n"," curr: the current partial solution\n"," ans: collect all the valide solutions\n"," '''\n"," if depth == k: #end condition\n"," ans.append(curr[::]) \n"," return\n"," \n"," for i in range(start, n): \n"," # generate the next solution from curr\n"," curr.append(a[i])\n"," # move to the next solution\n"," C_n_k(a, n, k, i+1, depth+1, curr, ans)\n","\n"," #backtrack to previous partial state\n"," curr.pop()\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"FQlAWNcp8-5y","colab_type":"code","outputId":"0dcbc55c-b228-4d99-f37f-5d44111f3183","executionInfo":{"status":"ok","timestamp":1553038549590,"user_tz":420,"elapsed":793,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["a = [1, 2, 3]\n","n = len(a)\n","ans = [[None]]\n","ans = []\n","C_n_k(a, n, 2, 0, 0, [], ans)\n","print(ans)\n"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1, 2], [1, 3], [2, 3]]\n"],"name":"stdout"}]},{"metadata":{"id":"ze7L-ttOgCUd","colab_type":"text"},"cell_type":"markdown","source":["### All paths"]},{"metadata":{"id":"jYkhLKk9QZqi","colab_type":"code","colab":{}},"cell_type":"code","source":["def all_paths(g, s, path, ans):\n"," '''generate all pahts with backtrack'''\n"," ans.append(path[::])\n"," for v in g[s]:\n"," path.append(v)\n"," print(path)\n"," all_paths(g, v, path, ans)\n"," path.pop()\n"," print(path, 'backtrack')"],"execution_count":0,"outputs":[]},{"metadata":{"id":"84vSh1JIQyLH","colab_type":"code","outputId":"809fc79d-57cb-4f5a-f444-7f8b41476e79","executionInfo":{"status":"ok","timestamp":1553038549595,"user_tz":420,"elapsed":757,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["al = [[1], [2], [4], [], [3, 5], [6], []]\n","print(al)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[[1], [2], [4], [], [3, 5], [6], []]\n"],"name":"stdout"}]},{"metadata":{"id":"HhBVClwEVeUJ","colab_type":"code","outputId":"1e88bace-af15-4632-b2c4-0cb9cedbe323","executionInfo":{"status":"ok","timestamp":1553038549597,"user_tz":420,"elapsed":740,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":256}},"cell_type":"code","source":["ans = []\n","path = [0]\n","all_paths(al, 0, path, ans)\n","print(ans)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[0, 1]\n","[0, 1, 2]\n","[0, 1, 2, 4]\n","[0, 1, 2, 4, 3]\n","[0, 1, 2, 4] backtrack\n","[0, 1, 2, 4, 5]\n","[0, 1, 2, 4, 5, 6]\n","[0, 1, 2, 4, 5] backtrack\n","[0, 1, 2, 4] backtrack\n","[0, 1, 2] backtrack\n","[0, 1] backtrack\n","[0] backtrack\n","[[0], [0, 1], [0, 1, 2], [0, 1, 2, 4], [0, 1, 2, 4, 3], [0, 1, 2, 4, 5], [0, 1, 2, 4, 5, 6]]\n"],"name":"stdout"}]},{"metadata":{"id":"7kLQciZ1Zt2i","colab_type":"text"},"cell_type":"markdown","source":["## Constraint Satisfaction Problems with Backtracking and Pruning"]},{"metadata":{"id":"oHsib-ORB9Fh","colab_type":"text"},"cell_type":"markdown","source":["First, we build up the board"]},{"metadata":{"id":"wU0IzGC8_EiP","colab_type":"code","colab":{}},"cell_type":"code","source":["board = [[5, 3, None, None, 7, None, None, None, None],\n"," [6, None, None, 1, 9, 5, None, None, None],\n"," [None, 9, 8, None, None, None, None, 6, None],\n"," [8, None, None, None, 6, None, None, None, 3], \n"," [4, None, None, 8, None, 3, None, None, 1], \n"," [7, None, None, None, 2, None, None, None, 6], \n"," [None, 6, None, None, None, None, 2, 8, None], \n"," [None, None, None, 4, 1, 9, None, None, 5],\n"," [None, None, None, None, 8, None, None, 7, 9]]"],"execution_count":0,"outputs":[]},{"metadata":{"id":"Psq2cedrMTGJ","colab_type":"text"},"cell_type":"markdown","source":["Define how to change the state"]},{"metadata":{"id":"t2oeCmmvCotc","colab_type":"code","colab":{}},"cell_type":"code","source":["def setState(i, j, v, row_state, col_state, grid_state):\n"," row_state[i] |= 1 << v\n"," col_state[j] |= 1 << v\n"," grid_index = (i//3)*3 + (j//3)\n"," grid_state[grid_index] |= 1 << v\n"," \n","def resetState(i, j, v, row_state, col_state, grid_state):\n"," row_state[i] &= ~(1 << v)\n"," col_state[j] &= ~(1 << v)\n"," grid_index = (i//3)*3 + (j//3)\n"," grid_state[grid_index] &= ~(1 << v)\n"," \n","def checkState(i, j, v, row_state, col_state, grid_state):\n"," row_bit = (1 << v) & row_state[i] != 0\n"," col_bit = (1 << v) & col_state[j] != 0\n"," grid_index = (i//3)*3 + (j//3)\n"," grid_bit = (1 << v) & grid_state[grid_index] != 0\n"," return not row_bit and not col_bit and not grid_bit"],"execution_count":0,"outputs":[]},{"metadata":{"id":"SgghNi99MWXw","colab_type":"text"},"cell_type":"markdown","source":["Get the empty spots and its values"]},{"metadata":{"id":"v0IZMZHU5FR-","colab_type":"code","colab":{}},"cell_type":"code","source":[" def getEmptySpots(board, rows, cols, row_state, col_state, grid_state): \n"," ''' get empty spots and find its corresponding values in O(n*n)'''\n"," empty_spots = {}\n"," # initialize the state, and get empty spots\n"," for i in range(rows):\n"," for j in range(cols):\n"," if board[i][j]:\n"," # set that bit to 1\n"," setState(i, j, board[i][j]-1, row_state, col_state, grid_state) \n"," else:\n"," empty_spots[(i,j)] = []\n"," \n"," # get possible values for each spot\n"," for i, j in empty_spots.keys():\n"," for v in range(9):\n"," if checkState(i, j, v, row_state, col_state, grid_state):\n"," empty_spots[(i, j)].append(v+1)\n"," \n"," return empty_spots"],"execution_count":0,"outputs":[]},{"metadata":{"id":"39DSr_mfCBrQ","colab_type":"text"},"cell_type":"markdown","source":["Second, we intialize the state and find empty spots. "]},{"metadata":{"id":"G76l_z6DAk4n","colab_type":"code","outputId":"1664fb47-2e89-46f7-c15c-47bff27bc873","executionInfo":{"status":"ok","timestamp":1553038549608,"user_tz":420,"elapsed":682,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":74}},"cell_type":"code","source":["# initialize state\n","row_state = [0]*9\n","col_state = [0]*9\n","grid_state = [0]*9\n","\n","empty_spots = getEmptySpots(board, 9, 9, row_state, col_state, grid_state)\n","print(row_state, col_state, grid_state) \n","sorted_empty_spots = sorted(empty_spots.items(), key=lambda x: len(x[1]))\n","print(sorted_empty_spots)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[84, 305, 416, 164, 141, 98, 162, 281, 448] [248, 292, 128, 137, 483, 276, 2, 224, 309] [436, 337, 32, 200, 166, 37, 32, 393, 466]\n","[((4, 4), [5]), ((6, 5), [7]), ((6, 8), [4]), ((7, 7), [3]), ((0, 3), [2, 6]), ((2, 0), [1, 2]), ((2, 3), [2, 3]), ((2, 4), [3, 4]), ((2, 5), [2, 4]), ((4, 1), [2, 5]), ((5, 1), [1, 5]), ((5, 3), [5, 9]), ((5, 5), [1, 4]), ((6, 4), [3, 5]), ((7, 0), [2, 3]), ((7, 6), [3, 6]), ((8, 5), [2, 6]), ((0, 2), [1, 2, 4]), ((0, 8), [2, 4, 8]), ((1, 1), [2, 4, 7]), ((1, 2), [2, 4, 7]), ((1, 7), [2, 3, 4]), ((2, 8), [2, 4, 7]), ((3, 1), [1, 2, 5]), ((3, 3), [5, 7, 9]), ((3, 5), [1, 4, 7]), ((4, 6), [5, 7, 9]), ((4, 7), [2, 5, 9]), ((5, 7), [4, 5, 9]), ((6, 0), [1, 3, 9]), ((6, 3), [3, 5, 7]), ((7, 1), [2, 7, 8]), ((7, 2), [2, 3, 7]), ((8, 0), [1, 2, 3]), ((0, 5), [2, 4, 6, 8]), ((0, 6), [1, 4, 8, 9]), ((0, 7), [1, 2, 4, 9]), ((1, 6), [3, 4, 7, 8]), ((1, 8), [2, 4, 7, 8]), ((3, 2), [1, 2, 5, 9]), ((3, 6), [4, 5, 7, 9]), ((3, 7), [2, 4, 5, 9]), ((4, 2), [2, 5, 6, 9]), ((5, 2), [1, 3, 5, 9]), ((5, 6), [4, 5, 8, 9]), ((8, 1), [1, 2, 4, 5]), ((8, 3), [2, 3, 5, 6]), ((8, 6), [1, 3, 4, 6]), ((2, 6), [1, 3, 4, 5, 7]), ((8, 2), [1, 2, 3, 4, 5]), ((6, 2), [1, 3, 4, 5, 7, 9])]\n"],"name":"stdout"}]},{"metadata":{"id":"jUPMX4-jF7N_","colab_type":"text"},"cell_type":"markdown","source":["Traverse the empty_spots, and fill in. "]},{"metadata":{"id":"ved6mk_0F6F-","colab_type":"code","colab":{}},"cell_type":"code","source":["def dfs_backtrack(empty_spots, index):\n"," if index == len(empty_spots):\n"," return True\n"," (i, j), vl = empty_spots[index]\n"," \n"," for v in vl: #try each value\n"," # check the state\n"," if checkState(i, j, v-1, row_state, col_state, grid_state):\n"," # set the state\n"," setState(i, j, v-1, row_state, col_state, grid_state)\n"," # mark the board\n"," board[i][j] = v\n"," if dfs_backtrack(empty_spots, index+1):\n"," return True\n"," else:\n"," #backtack to previouse state\n"," resetState(i, j, v-1, row_state, col_state, grid_state)\n"," #unmark the board\n"," board[i][j] = None\n"," return False\n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"QUr5dZQxIpdn","colab_type":"code","outputId":"0d08b439-e745-478d-98e8-84498f033412","executionInfo":{"status":"ok","timestamp":1553038549612,"user_tz":420,"elapsed":656,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":74}},"cell_type":"code","source":["ans = dfs_backtrack(sorted_empty_spots, 0)\n","print(ans)\n","print(board)"],"execution_count":0,"outputs":[{"output_type":"stream","text":["True\n","[[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8], [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3], [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6], [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5], [3, 4, 5, 2, 8, 6, 1, 7, 9]]\n"],"name":"stdout"}]},{"metadata":{"id":"4vOhZxglCBKD","colab_type":"text"},"cell_type":"markdown","source":["#### Sudoku Solver"]},{"metadata":{"id":"j7d_45x3MiY9","colab_type":"code","colab":{}},"cell_type":"code","source":["from copy import deepcopy\n","import time\n","class SudokoSolver():\n"," def __init__(self, board):\n"," self.original_board = deepcopy(board)\n"," self.board = deepcopy(board)\n"," self.n = len(board)\n"," assert (self.n == len(board[0]))\n"," # initialize state\n"," self.row_state = [0]*self.n\n"," self.col_state = [0]*self.n\n"," self.grid_state = [0]*self.n\n"," \n"," def _setState(self, i, j, v):\n"," self.row_state[i] |= 1 << v\n"," self.col_state[j] |= 1 << v\n"," grid_index = (i//3)*3 + (j//3)\n"," self.grid_state[grid_index] |= 1 << v\n"," \n"," def _resetState(self, i, j, v):\n"," self.row_state[i] &= ~(1 << v)\n"," self.col_state[j] &= ~(1 << v)\n"," grid_index = (i//3)*3 + (j//3)\n"," self.grid_state[grid_index] &= ~(1 << v)\n"," \n"," def _checkState(self, i, j, v):\n"," row_bit = (1 << v) & self.row_state[i] != 0\n"," col_bit = (1 << v) & self.col_state[j] != 0\n"," grid_index = (i//3)*3 + (j//3)\n"," grid_bit = (1 << v) & self.grid_state[grid_index] != 0\n"," return not row_bit and not col_bit and not grid_bit\n"," \n"," def reset(self):\n"," # initialize state\n"," self.row_state = [0]*self.n\n"," self.col_state = [0]*self.n\n"," self.grid_state = [0]*self.n\n"," self.board = deepcopy(self.original_board)\n"," \n"," def _getEmptySpots(self): \n"," ''' get empty spots and find its corresponding values in O(n*n)'''\n"," empty_spots = {}\n"," # initialize the state, and get empty spots\n"," for i in range(self.n):\n"," for j in range(self.n):\n"," if self.board[i][j]:\n"," # set that bit to 1\n"," self._setState(i, j, self.board[i][j]-1) \n"," else:\n"," empty_spots[(i,j)] = []\n"," \n"," # get possible values for each spot\n"," for i, j in empty_spots.keys():\n"," for v in range(self.n):\n"," if self._checkState(i, j, v):\n"," empty_spots[(i, j)].append(v+1)\n"," \n"," return empty_spots\n"," \n"," def helper(self, empty_spots, index):\n"," if index == len(empty_spots):\n"," return True\n"," (i, j), vl = empty_spots[index]\n"," \n"," for v in vl: #try each value\n"," # check the state\n"," if self._checkState(i, j, v-1):\n"," # set the state\n"," self._setState(i, j, v-1)\n"," # mark the board\n"," self.board[i][j] = v\n"," if self.helper(empty_spots, index+1):\n"," return True\n"," else:\n"," #backtack to previouse state\n"," self._resetState(i, j, v-1)\n"," #unmark the board\n"," self.board[i][j] = None\n"," return False\n"," \n"," def backtrackSolver(self):\n"," self.reset()\n"," empty_spots = self._getEmptySpots()\n"," empty_spots = [(k, v) for k, v in empty_spots.items() ]\n"," t0 = time.time()\n"," ans = self.helper(empty_spots, 0)\n"," print('total time: ', time.time() - t0)\n"," return ans\n"," \n"," def backtrackSolverSorted(self):\n"," self.reset()\n"," empty_spots = self._getEmptySpots()\n"," empty_spots = sorted(empty_spots.items(), key=lambda x: len(x[1]))\n"," t0 = time.time()\n"," ans = self.helper(empty_spots, 0)\n"," print('sorted total time: ', time.time() - t0)\n"," return ans\n","\n"," \n"," \n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"zIti82qiQ7Je","colab_type":"code","outputId":"c8220407-50a1-426d-a2df-cc6d005b497d","executionInfo":{"status":"ok","timestamp":1553038549788,"user_tz":420,"elapsed":786,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":72}},"cell_type":"code","source":["board = [[5, 3, None, None, 7, None, None, None, None],\n"," [6, None, None, 1, 9, 5, None, None, None],\n"," [None, 9, 8, None, None, None, None, 6, None],\n"," [8, None, None, None, 6, None, None, None, 3], \n"," [4, None, None, 8, None, 3, None, None, 1], \n"," [7, None, None, None, 2, None, None, None, 6], \n"," [None, 6, None, None, None, None, 2, 8, None], \n"," [None, None, None, 4, 1, 9, None, None, 5],\n"," [None, None, None, None, 8, None, None, 7, 9]]\n","solver = SudokoSolver(board)\n","solver.backtrackSolver()\n","solver.backtrackSolverSorted()"],"execution_count":0,"outputs":[{"output_type":"stream","text":["total time: 0.027954578399658203\n","sorted total time: 0.0004558563232421875\n"],"name":"stdout"},{"output_type":"execute_result","data":{"text/plain":["True"]},"metadata":{"tags":[]},"execution_count":239}]}]} -------------------------------------------------------------------------------- /chapter_tree_data_structure_and_traversal.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "chapter_tree_data_structure_and_traversal.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [], 9 | "toc_visible": true 10 | }, 11 | "kernelspec": { 12 | "name": "python3", 13 | "display_name": "Python 3" 14 | } 15 | }, 16 | "cells": [ 17 | { 18 | "cell_type": "markdown", 19 | "metadata": { 20 | "id": "3A2mprldYvXe", 21 | "colab_type": "text" 22 | }, 23 | "source": [ 24 | "## Tree Representation\n" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": { 30 | "id": "SYVbYid7SPos", 31 | "colab_type": "text" 32 | }, 33 | "source": [ 34 | "### N-aray Tree" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "metadata": { 40 | "id": "9R_XYWC2Yz-G", 41 | "colab_type": "code", 42 | "colab": {} 43 | }, 44 | "source": [ 45 | "# Define Tree Node\n", 46 | "class NaryNode:\n", 47 | " def __init__(self, val, n):\n", 48 | " self.children = [None] * n\n", 49 | " self.val = val " 50 | ], 51 | "execution_count": 0, 52 | "outputs": [] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "metadata": { 57 | "id": "cQfD7fA7WWPT", 58 | "colab_type": "code", 59 | "colab": {} 60 | }, 61 | "source": [ 62 | "root = NaryNode(1, 2)\n", 63 | "left = NaryNode(2, 2)\n", 64 | "right = NaryNode(3, 2)\n", 65 | "# connect root to its left and right, the order does not matter\n", 66 | "root.children[0] = left\n", 67 | "root.children[1] = right\n", 68 | "left = NaryNode(4, 0)\n", 69 | "right = NaryNode(5, 5)" 70 | ], 71 | "execution_count": 0, 72 | "outputs": [] 73 | }, 74 | { 75 | "cell_type": "markdown", 76 | "metadata": { 77 | "id": "wLPjQrfnZbQY", 78 | "colab_type": "text" 79 | }, 80 | "source": [ 81 | "### Binary Tree" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "metadata": { 87 | "id": "ZKknhNURZdA0", 88 | "colab_type": "code", 89 | "colab": {} 90 | }, 91 | "source": [ 92 | "# Binary Tree Node\n", 93 | "class BinaryNode:\n", 94 | " def __init__(self, val):\n", 95 | " self.left = None\n", 96 | " self.right = None\n", 97 | " self.val = val" 98 | ], 99 | "execution_count": 0, 100 | "outputs": [] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "metadata": { 105 | "id": "yPukXXkXZ_zn", 106 | "colab_type": "text" 107 | }, 108 | "source": [ 109 | "#### Tree Construction\n", 110 | "```\n", 111 | " 1\n", 112 | " / \\ \n", 113 | " 2 3\n", 114 | " / \\ \\\n", 115 | "4 5 6 \n", 116 | "```" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "metadata": { 122 | "id": "CyXwZ9sf8dyG", 123 | "colab_type": "code", 124 | "colab": {} 125 | }, 126 | "source": [ 127 | "# Naive Tree Construction\n", 128 | "root = BinaryNode(1)\n", 129 | "left = BinaryNode(2)\n", 130 | "right = BinaryNode(3)\n", 131 | "root.left = left\n", 132 | "root.right = right\n", 133 | "left.left = BinaryNode(4)\n", 134 | "left.right = BinaryNode(5)\n", 135 | "right.right = BinaryNode(6)" 136 | ], 137 | "execution_count": 0, 138 | "outputs": [] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "metadata": { 143 | "id": "gOHqKKfY_Ug0", 144 | "colab_type": "code", 145 | "colab": {} 146 | }, 147 | "source": [ 148 | "# Recursive Tree Construction\n", 149 | "def constructTree(a, idx):\n", 150 | " '''\n", 151 | " a: input array of nodes\n", 152 | " idx: index to indicat the location of the current node\n", 153 | " '''\n", 154 | " if idx >= len(a):\n", 155 | " return None\n", 156 | " if a[idx]:\n", 157 | " node = BinaryNode(a[idx])\n", 158 | " node.left = constructTree(a, 2*idx + 1)\n", 159 | " node.right = constructTree(a, 2*idx + 2)\n", 160 | " return node\n", 161 | " return None" 162 | ], 163 | "execution_count": 0, 164 | "outputs": [] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "metadata": { 169 | "id": "STvuN-5p_5Di", 170 | "colab_type": "code", 171 | "colab": {} 172 | }, 173 | "source": [ 174 | "nums = [1, 2, 3, 4, 5, None, 6]\n", 175 | "root = constructTree(nums, 0)" 176 | ], 177 | "execution_count": 0, 178 | "outputs": [] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "metadata": { 183 | "id": "NsyaTExQIAos", 184 | "colab_type": "code", 185 | "outputId": "1681353d-30ad-4269-d273-cf939958e015", 186 | "colab": { 187 | "base_uri": "https://localhost:8080/", 188 | "height": 35 189 | } 190 | }, 191 | "source": [ 192 | "nums = [1] * 1_000_000\n", 193 | "print(nums.__sizeof__()/1024/1024)" 194 | ], 195 | "execution_count": 0, 196 | "outputs": [ 197 | { 198 | "output_type": "stream", 199 | "text": [ 200 | "7.629432678222656\n" 201 | ], 202 | "name": "stdout" 203 | } 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "metadata": { 209 | "id": "D4Bj_uMsHpAZ", 210 | "colab_type": "code", 211 | "colab": {} 212 | }, 213 | "source": [ 214 | "# Constrcut a large tree\n", 215 | "nums = [1] * 1_000_000\n", 216 | "#root = constructTree(nums, 0)" 217 | ], 218 | "execution_count": 0, 219 | "outputs": [] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": { 224 | "id": "ymohgmrC9-ih", 225 | "colab_type": "text" 226 | }, 227 | "source": [ 228 | "## Tree Traversal" 229 | ] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "metadata": { 234 | "id": "W4XlEDMn7ZE5", 235 | "colab_type": "text" 236 | }, 237 | "source": [ 238 | "### Depth-first Tree Traversal" 239 | ] 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "metadata": { 244 | "id": "U_ZjljRzugyQ", 245 | "colab_type": "text" 246 | }, 247 | "source": [ 248 | "#### Recursive Tree Traversal" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "metadata": { 254 | "id": "zERenCBy99sV", 255 | "colab_type": "code", 256 | "colab": {} 257 | }, 258 | "source": [ 259 | "# Preorder Traversal\n", 260 | "def recursive(node):\n", 261 | " if not node:\n", 262 | " return\n", 263 | " print(node.val, end=' ')\n", 264 | " recursive(node.left)\n", 265 | " recursive(node.right)\n" 266 | ], 267 | "execution_count": 0, 268 | "outputs": [] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "metadata": { 273 | "id": "M86_7JR7-cfu", 274 | "colab_type": "code", 275 | "outputId": "46132bdc-06ad-406b-8db4-ff08febe0a89", 276 | "colab": { 277 | "base_uri": "https://localhost:8080/", 278 | "height": 35 279 | } 280 | }, 281 | "source": [ 282 | "recursive(root)" 283 | ], 284 | "execution_count": 0, 285 | "outputs": [ 286 | { 287 | "output_type": "stream", 288 | "text": [ 289 | "1 2 4 5 3 6 " 290 | ], 291 | "name": "stdout" 292 | } 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "metadata": { 298 | "id": "o1U3R9A8GvPr", 299 | "colab_type": "code", 300 | "colab": {} 301 | }, 302 | "source": [ 303 | "# Inorder Traversal\n", 304 | "def inorder_traversal(node):\n", 305 | " if not node:\n", 306 | " return\n", 307 | " inorder_traversal(node.left)\n", 308 | " print(node.val, end=' ')\n", 309 | " inorder_traversal(node.right)" 310 | ], 311 | "execution_count": 0, 312 | "outputs": [] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "metadata": { 317 | "id": "sy6hIovuG0dq", 318 | "colab_type": "code", 319 | "outputId": "ab4403e1-b5ac-4747-a388-30a79f2f2bc6", 320 | "colab": { 321 | "base_uri": "https://localhost:8080/", 322 | "height": 35 323 | } 324 | }, 325 | "source": [ 326 | "inorder_traversal(root)" 327 | ], 328 | "execution_count": 0, 329 | "outputs": [ 330 | { 331 | "output_type": "stream", 332 | "text": [ 333 | "4 2 5 1 3 6 " 334 | ], 335 | "name": "stdout" 336 | } 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "metadata": { 342 | "id": "Si1c44bDKLkG", 343 | "colab_type": "code", 344 | "colab": {} 345 | }, 346 | "source": [ 347 | "# Preorder traversal with returns\n", 348 | "def PreOrder(root):\n", 349 | " if root is None:\n", 350 | " return []\n", 351 | " ans = []\n", 352 | " # Divide and brings back the subresult\n", 353 | " left = PreOrder(root.left)\n", 354 | " right = PreOrder(root.right)\n", 355 | " # Combine\n", 356 | " ans = [root.val] + left + right\n", 357 | " return ans" 358 | ], 359 | "execution_count": 0, 360 | "outputs": [] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "metadata": { 365 | "id": "tCVpSw9ALNEM", 366 | "colab_type": "code", 367 | "outputId": "30f7cb20-2abd-4a00-f978-e4609d2d6300", 368 | "colab": { 369 | "base_uri": "https://localhost:8080/", 370 | "height": 35 371 | } 372 | }, 373 | "source": [ 374 | "print(PreOrder(root))" 375 | ], 376 | "execution_count": 0, 377 | "outputs": [ 378 | { 379 | "output_type": "stream", 380 | "text": [ 381 | "[1, 2, 4, 5, 3, 6]\n" 382 | ], 383 | "name": "stdout" 384 | } 385 | ] 386 | }, 387 | { 388 | "cell_type": "markdown", 389 | "metadata": { 390 | "id": "yxCOd-iZuc-s", 391 | "colab_type": "text" 392 | }, 393 | "source": [ 394 | "#### Iterative Tree Traversal" 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "metadata": { 400 | "id": "N43NhcugSfYN", 401 | "colab_type": "code", 402 | "colab": {} 403 | }, 404 | "source": [ 405 | "def PreOrderIterative(root):\n", 406 | " if root is None:\n", 407 | " return []\n", 408 | " res = []\n", 409 | " stack = [root]\n", 410 | " while stack:\n", 411 | " tmp = stack.pop()\n", 412 | " res.append(tmp.val)\n", 413 | " if tmp.right:\n", 414 | " stack.append(tmp.right)\n", 415 | " if tmp.left:\n", 416 | " stack.append(tmp.left)\n", 417 | " return res" 418 | ], 419 | "execution_count": 0, 420 | "outputs": [] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "metadata": { 425 | "id": "5ay0zisQShpr", 426 | "colab_type": "code", 427 | "colab": {} 428 | }, 429 | "source": [ 430 | "preorders = PreOrderIterative(root)\n", 431 | "preorders" 432 | ], 433 | "execution_count": 0, 434 | "outputs": [] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "metadata": { 439 | "id": "iz2S46vA7ked", 440 | "colab_type": "code", 441 | "colab": {} 442 | }, 443 | "source": [ 444 | "def PostOrderIterative(root):\n", 445 | " if root is None:\n", 446 | " return []\n", 447 | " res = []\n", 448 | " stack = [root]\n", 449 | " while stack:\n", 450 | " tmp = stack.pop()\n", 451 | " res.append(tmp.val)\n", 452 | " if tmp.left:\n", 453 | " stack.append(tmp.left)\n", 454 | " if tmp.right:\n", 455 | " stack.append(tmp.right)\n", 456 | " return res[::-1]" 457 | ], 458 | "execution_count": 0, 459 | "outputs": [] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "metadata": { 464 | "id": "_SH4Cr6c7sP5", 465 | "colab_type": "code", 466 | "outputId": "7d956975-f3e2-46e3-d9d2-fe10c41bc8c6", 467 | "colab": { 468 | "base_uri": "https://localhost:8080/", 469 | "height": 35 470 | } 471 | }, 472 | "source": [ 473 | "postorders = PostOrderIterative(root)\n", 474 | "postorders" 475 | ], 476 | "execution_count": 0, 477 | "outputs": [ 478 | { 479 | "output_type": "execute_result", 480 | "data": { 481 | "text/plain": [ 482 | "[4, 5, 2, 6, 3, 1]" 483 | ] 484 | }, 485 | "metadata": { 486 | "tags": [] 487 | }, 488 | "execution_count": 22 489 | } 490 | ] 491 | }, 492 | { 493 | "cell_type": "code", 494 | "metadata": { 495 | "id": "cxWckHgZupxE", 496 | "colab_type": "code", 497 | "colab": {} 498 | }, 499 | "source": [ 500 | "# Inorder and Preorder\n", 501 | "def iterative_traversal(root):\n", 502 | " stack = []\n", 503 | " cur = root\n", 504 | " preorders = []\n", 505 | " inorders = []\n", 506 | " while stack or cur:\n", 507 | " while cur:\n", 508 | " preorders.append(cur.val)\n", 509 | " stack.append(cur)\n", 510 | " cur = cur.left\n", 511 | " node = stack.pop()\n", 512 | " inorders.append(node.val)\n", 513 | " cur = node.right\n", 514 | " return preorders, inorders" 515 | ], 516 | "execution_count": 0, 517 | "outputs": [] 518 | }, 519 | { 520 | "cell_type": "code", 521 | "metadata": { 522 | "id": "TFuu6oUmwwDq", 523 | "colab_type": "code", 524 | "outputId": "c54bfafe-5789-4538-a6bf-5a4f843ab75d", 525 | "colab": { 526 | "base_uri": "https://localhost:8080/", 527 | "height": 35 528 | } 529 | }, 530 | "source": [ 531 | "preorders, inorders = iterative_traversal(root)\n", 532 | "preorders, inorders" 533 | ], 534 | "execution_count": 0, 535 | "outputs": [ 536 | { 537 | "output_type": "execute_result", 538 | "data": { 539 | "text/plain": [ 540 | "([1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6])" 541 | ] 542 | }, 543 | "metadata": { 544 | "tags": [] 545 | }, 546 | "execution_count": 20 547 | } 548 | ] 549 | }, 550 | { 551 | "cell_type": "markdown", 552 | "metadata": { 553 | "id": "GyJug1-77Re6", 554 | "colab_type": "text" 555 | }, 556 | "source": [ 557 | "### Breath-first Tree Traversal" 558 | ] 559 | }, 560 | { 561 | "cell_type": "code", 562 | "metadata": { 563 | "id": "8IxSoqTthZb9", 564 | "colab_type": "code", 565 | "colab": {} 566 | }, 567 | "source": [ 568 | "# Level Order Traversal: To show the nodes at each level, we use LevelOrder function to print out the tree:\n", 569 | "def LevelOrder(root):\n", 570 | " if not root:\n", 571 | " return\n", 572 | " nodes_same_level = [root]\n", 573 | " while nodes_same_level:\n", 574 | " temp = []\n", 575 | " for n in nodes_same_level:\n", 576 | " print(n.val, end=' ')\n", 577 | " if n.left:\n", 578 | " temp.append(n.left)\n", 579 | " if n.right:\n", 580 | " temp.append(n.right)\n", 581 | " nodes_same_level = temp" 582 | ], 583 | "execution_count": 0, 584 | "outputs": [] 585 | }, 586 | { 587 | "cell_type": "code", 588 | "metadata": { 589 | "id": "uPxVdjRrA0UB", 590 | "colab_type": "code", 591 | "colab": {} 592 | }, 593 | "source": [ 594 | "# Use a queue\n", 595 | "def bfs(root):\n", 596 | " if not root:\n", 597 | " return\n", 598 | " q = [root]\n", 599 | " while q:\n", 600 | " node = q.pop(0) # get node at the front of the queue\n", 601 | " print(node.val, end=' ')\n", 602 | " if node.left:\n", 603 | " q.append(node.left)\n", 604 | " if node.right:\n", 605 | " q.append(node.right)\n" 606 | ], 607 | "execution_count": 0, 608 | "outputs": [] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "metadata": { 613 | "id": "Pl2HGcHkA4rT", 614 | "colab_type": "code", 615 | "outputId": "9df917c4-592e-4233-b48f-502ceef94f27", 616 | "colab": { 617 | "base_uri": "https://localhost:8080/", 618 | "height": 35 619 | } 620 | }, 621 | "source": [ 622 | "LevelOrder(root)" 623 | ], 624 | "execution_count": 0, 625 | "outputs": [ 626 | { 627 | "output_type": "stream", 628 | "text": [ 629 | "1 2 3 4 5 6 " 630 | ], 631 | "name": "stdout" 632 | } 633 | ] 634 | } 635 | ] 636 | } -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/chapter_14_sorting.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"chapter_14_sorting.ipynb","version":"0.3.2","provenance":[],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"XOkspIkgKots","colab_type":"text"},"cell_type":"markdown","source":["## Counting Sorting in O(n+k)"]},{"metadata":{"id":"ptAUeFu8Kvrs","colab_type":"code","colab":{}},"cell_type":"code","source":["def countSort(a):\n"," minK, maxK = min(a), max(a)\n"," k = maxK - minK + 1\n"," count = [0] * (maxK - minK + 1)\n"," n = len(a)\n"," order = [0] * n\n"," # get occurrence\n"," for key in a:\n"," count[key - minK] += 1\n"," \n"," # get prefix sum\n"," for i in range(1, k):\n"," count[i] += count[i-1]\n"," \n"," # put it back in the input\n"," for i in range(n-1, -1, -1):\n"," key = a[i] - minK\n"," count[key] -= 1 # to get the index as position\n"," order[count[key]] = a[i] # put the key back to the sorted position\n"," return order"],"execution_count":0,"outputs":[]},{"metadata":{"id":"IUEe34hHMqBx","colab_type":"code","outputId":"b5074a60-b9b8-4313-ca63-1ba44addd461","executionInfo":{"status":"ok","timestamp":1550259045549,"user_tz":480,"elapsed":271,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":34}},"cell_type":"code","source":["a = [9, 10, 2, 8, 9, 3, 7]\n","print(countSort(a))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[2, 3, 7, 8, 9, 9, 10]\n"],"name":"stdout"}]},{"metadata":{"id":"lHFCwzZNGrMu","colab_type":"text"},"cell_type":"markdown","source":["## Bubble Sort in O(n^2)"]},{"metadata":{"id":"uqzSlyDXGzhO","colab_type":"code","colab":{}},"cell_type":"code","source":["def bubbleSort(a):\n"," if not a or len(a) == 1:\n"," return a\n"," n = len(a)\n"," for i in range(n - 1): #n-1 passes, \n"," for j in range(n - i -1): #each pass will have valid window [0, n-i], and j is the starting index of each pair\n"," if a[j] > a[j + 1]:\n"," a[j], a[j + 1] = a[j + 1], a[j] #swap\n"," return a"],"execution_count":0,"outputs":[]},{"metadata":{"id":"B-WK_VNi_unM","colab_type":"code","colab":{}},"cell_type":"code","source":["def bubbleSortOptimized(a):\n"," if not a or len(a) == 1:\n"," return a\n"," n = len(a)\n"," for i in range(n - 1): #n-1 passes, \n"," bSwap = False\n"," for j in range(n - i -1): #each pass will have valid window [0, n-i], and j is the starting index of each pair\n"," if a[j] > a[j + 1]:\n"," a[j], a[j + 1] = a[j + 1], a[j] #swap\n"," bSwap = True\n"," if not bSwap:\n"," break\n"," return a"],"execution_count":0,"outputs":[]},{"metadata":{"id":"npb5NRJdI4sV","colab_type":"code","outputId":"57c48506-47f9-4d27-cad6-b93c3729e4c5","executionInfo":{"status":"ok","timestamp":1550350492596,"user_tz":480,"elapsed":323,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["a = [9, 10, 2, 8, 9, 3, 7]\n","print(bubbleSortOptimized(a))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[2, 3, 7, 8, 9, 9, 10]\n"],"name":"stdout"}]},{"metadata":{"id":"RZwzr_7xBjae","colab_type":"text"},"cell_type":"markdown","source":["## Selection Sort in O(n^2)"]},{"metadata":{"id":"e0U-HGHcBpL4","colab_type":"code","colab":{}},"cell_type":"code","source":["def selectSort(a):\n"," n = len(a)\n"," for i in range(n - 1): #n-1 passes, \n"," ti = n - 1 -i # the position to fill in the largest item of valid window [0, n-i]\n"," li = 0\n"," for j in range(n - i):\n"," if a[j] > a[li]:\n"," li = j\n"," # swap li and ti\n"," print('swap', a[li], a[ti])\n"," a[ti], a[li] = a[li], a[ti]\n"," print(a)\n"," return a\n"," \n"," \n"," #"],"execution_count":0,"outputs":[]},{"metadata":{"id":"r3v62LNjEZVY","colab_type":"code","outputId":"7d4a8ad0-466f-4ff4-dd2f-e214c7979e3e","executionInfo":{"status":"ok","timestamp":1550350715349,"user_tz":480,"elapsed":388,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":256}},"cell_type":"code","source":["a = [9, 10, 2, 8, 9, 3, 9]\n","print(selectSort(a))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["swap 10 9\n","[9, 9, 2, 8, 9, 3, 10]\n","swap 9 3\n","[3, 9, 2, 8, 9, 9, 10]\n","swap 9 9\n","[3, 9, 2, 8, 9, 9, 10]\n","swap 9 8\n","[3, 8, 2, 9, 9, 9, 10]\n","swap 8 2\n","[3, 2, 8, 9, 9, 9, 10]\n","swap 3 2\n","[2, 3, 8, 9, 9, 9, 10]\n","[2, 3, 8, 9, 9, 9, 10]\n"],"name":"stdout"}]},{"metadata":{"id":"IQcElo1mM_Sf","colab_type":"text"},"cell_type":"markdown","source":["## Insertion Sort in O(n^2)"]},{"metadata":{"id":"yJL27nHcNEJl","colab_type":"code","colab":{}},"cell_type":"code","source":["def insertionSort(a):\n"," if not a or len(a) == 1:\n"," return a\n"," n = len(a)\n"," sl = [a[0]] # sorted list\n"," for i in range(1, n): # items to be inserted into the sorted\n"," j = 0 \n"," while j < len(sl):\n"," if a[i] > sl[j]:\n"," j += 1\n"," else:\n"," sl.insert(j, a[i])\n"," break\n"," if j == len(sl): # not inserted yet\n"," sl.insert(j, a[i])\n"," return sl\n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"Zb5jMt-iScSz","colab_type":"code","outputId":"766ddcce-178d-4832-d154-e853a03debaa","executionInfo":{"status":"ok","timestamp":1550259083716,"user_tz":480,"elapsed":283,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":221}},"cell_type":"code","source":["a = [9, 10, 2, 8, 9, 3, 7]\n","print(insertionSort(a))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[9, 10]\n","[2, 9, 10]\n","[2, 9, 10]\n","[2, 8, 9, 10]\n","[2, 8, 9, 10]\n","[2, 8, 9, 9, 10]\n","[2, 8, 9, 9, 10]\n","[2, 3, 8, 9, 9, 10]\n","[2, 3, 8, 9, 9, 10]\n","[2, 3, 7, 8, 9, 9, 10]\n","[2, 3, 7, 8, 9, 9, 10]\n","[2, 3, 7, 8, 9, 9, 10]\n"],"name":"stdout"}]},{"metadata":{"id":"EI1bDD3106fV","colab_type":"code","colab":{}},"cell_type":"code","source":["def shift(a, start, end):\n"," for i in range(end, start, -1): # [i, j)\n"," a[i] = a[i-1]\n"," \n","def insertionSortForward(a):\n"," if not a or len(a) == 1:\n"," return a\n"," n = len(a)\n"," sl = [a[0]] # sorted list\n"," for i in range(1, n): # items to be inserted into the sorted\n"," for j in range(i):\n"," if a[i] < a[j]:\n"," # shift all other elements [j, i-1]\n"," tmp = a[i]\n"," shift(a, j, i)\n"," a[j] = tmp \n"," return a\n","\n","def insertionSortInPlace(a):\n"," if not a or len(a) == 1:\n"," return a\n"," n = len(a)\n"," for i in range(1, n): # items to be inserted into the sorted\n"," t = a[i]\n"," j = i - 1\n"," while j >= 0 and t < a[j]: # keep comparing if target is still smaller\n"," a[j+1] = a[j] # shift current item backward\n"," j -= 1\n"," a[j+1] = t # a[j] <= t , insert t at the location j+1 \n"," return a"],"execution_count":0,"outputs":[]},{"metadata":{"id":"NgeLGKn51mxY","colab_type":"code","outputId":"6051e043-4c10-48c3-d477-10bb3b13a05b","executionInfo":{"status":"ok","timestamp":1550348226402,"user_tz":480,"elapsed":325,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["a = [9, 10, 2, 8, 9, 3, 7]\n","print(insertionSortInPlace(a))"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[2, 3, 7, 8, 9, 9, 10]\n"],"name":"stdout"}]},{"metadata":{"id":"GN1yseSKImNy","colab_type":"text"},"cell_type":"markdown","source":["## Merge Sort O(nlgn)"]},{"metadata":{"id":"rILA4lBhdPxD","colab_type":"code","colab":{}},"cell_type":"code","source":["def merge(l, r): \n"," '''combine the left and right sorted list'''\n"," ans = []\n"," i = j = 0 # two pointers each points at l and r\n"," n, m = len(l), len(r)\n"," \n"," # first while loop to merge\n"," while i < n and j < m: \n"," if l[i] <= r[j]:\n"," ans.append(l[i])\n"," i += 1\n"," else:\n"," ans.append(r[j])\n"," j += 1\n"," \n"," # now one list of l and r might have items left\n"," ans += l[i:]\n"," ans += r[j:]\n"," return ans\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"DK003Ic1Isb3","colab_type":"code","colab":{}},"cell_type":"code","source":["def mergeSort(a, s, e):\n"," # base case , can not be divided further\n"," if s == e:\n"," return [a[s]]\n"," # divide into two halves from the middle point\n"," m = (s + e) // 2\n"," \n"," # conquer\n"," l = mergeSort(a, s , m)\n"," r = mergeSort(a, m+1, e)\n"," \n"," # combine\n"," return merge(l, r)"],"execution_count":0,"outputs":[]},{"metadata":{"id":"ys6tUAd8i7ao","colab_type":"code","outputId":"afc20a0d-012e-413f-baf1-f098bb8e23ce","executionInfo":{"status":"ok","timestamp":1550374945810,"user_tz":480,"elapsed":336,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["a = [9, 10, 2, 8, 9, 3, 7, 9]\n","mergeSort(a, 0, len(a)-1)"],"execution_count":0,"outputs":[{"output_type":"execute_result","data":{"text/plain":["[2, 3, 7, 8, 9, 9, 9, 10]"]},"metadata":{"tags":[]},"execution_count":34}]},{"metadata":{"id":"IL6hPk6IjGSf","colab_type":"text"},"cell_type":"markdown","source":["### prove merge sort is stable by sorting tuple and printing id"]},{"metadata":{"id":"UwgdFdaRipEN","colab_type":"code","colab":{}},"cell_type":"code","source":["def mergeTuple(l, r): \n"," '''combine the left and right sorted list'''\n"," ans = []\n"," i = j = 0 # two pointers each points at l and r\n"," n, m = len(l), len(r)\n"," \n"," # first while loop to merge\n"," while i < n and j < m: \n"," if l[i][0] <= r[j][0]: # chaning it to l[i][0] < r[j][0] will not be stable anymore. \n"," ans.append(l[i])\n"," i += 1\n"," else:\n"," ans.append(r[j])\n"," j += 1\n"," \n"," # now one list of l and r might have items left\n"," ans += l[i:]\n"," ans += r[j:]\n"," return ans\n","\n","def mergeSortTuple(a, s, e):\n"," # base case , can not be divided further\n"," if s == e:\n"," return [a[s]]\n"," # divide into two halves from the middle point\n"," m = (s + e) // 2\n"," \n"," # conquer\n"," l = mergeSort(a, s , m)\n"," r = mergeSort(a, m+1, e)\n"," \n"," # combine\n"," return mergeTuple(l, r)"],"execution_count":0,"outputs":[]},{"metadata":{"id":"mm07Ac0-dO3A","colab_type":"code","outputId":"dd9eca57-98b7-4e04-acc2-7a31e7efd61d","executionInfo":{"status":"ok","timestamp":1550378993589,"user_tz":480,"elapsed":914,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":312}},"cell_type":"code","source":["a = [(9, 1), (10, 1), (2, 1), (8, 1), (9, 2), (3, 1), (7, 1), (9, 3)] # the second item represents the index of duplcates\n","ids = [id(x) if x[0] == 9 else None for x in a]\n","sorted_a = mergeSortTuple(a, 0, len(a)-1)\n","ids2 = [id(x) if x[0] == 9 else None for x in sorted_a]\n","print(sorted_a)\n","ids, ids2"],"execution_count":0,"outputs":[{"output_type":"stream","text":["[(2, 1), (3, 1), (7, 1), (8, 1), (9, 2), (9, 3), (9, 1), (10, 1)]\n"],"name":"stdout"},{"output_type":"execute_result","data":{"text/plain":["([140381548618120,\n"," None,\n"," None,\n"," None,\n"," 140381548653128,\n"," None,\n"," None,\n"," 140381548653320],\n"," [None,\n"," None,\n"," None,\n"," None,\n"," 140381548653128,\n"," 140381548653320,\n"," 140381548618120,\n"," None])"]},"metadata":{"tags":[]},"execution_count":47}]},{"metadata":{"id":"h0QYWQaDxt9D","colab_type":"text"},"cell_type":"markdown","source":["## QuickSort in O(nlogn)"]},{"metadata":{"id":"j4mW9xNrO6hm","colab_type":"code","colab":{}},"cell_type":"code","source":["def partition(a, s, e):\n"," '''Lumutos partition'''\n"," p = a[e]\n"," i = s - 1\n"," for j in range(s, e): #a[s, e-1]\n"," \n"," if a[j] <= p:\n"," i += 1\n"," a[i], a[j] = a[j], a[i] # swap a[i] and a[j]\n"," # print out the range of each region\n","# print('p<->i', [a[x] for x in range(s, i+1)])\n","# print('i+1<->j', [a[x] for x in range(i+1, j+1)])\n"," # place p at position i+1 through swapping with a[i+1]\n"," a[i+1], a[e] = a[e], a[i+1]\n"," return i+1"],"execution_count":0,"outputs":[]},{"metadata":{"id":"YPUErvQ1pT1v","colab_type":"text"},"cell_type":"markdown","source":["### experiment the correctness of lumutos partition"]},{"metadata":{"id":"oTmEOjk2QQZV","colab_type":"code","outputId":"cc8a3971-7ef6-45b4-da03-d2c46460ffcf","executionInfo":{"status":"ok","timestamp":1550560957592,"user_tz":480,"elapsed":474,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["lst = [9, 10, 2, 8, 9, 3, 7]\n","print(partition(lst, 0, len(lst)-1))\n","print(lst)"],"execution_count":37,"outputs":[{"output_type":"stream","text":["2\n","[2, 3, 7, 8, 9, 10, 9]\n"],"name":"stdout"}]},{"metadata":{"id":"qi_gd9TQpbn_","colab_type":"text"},"cell_type":"markdown","source":["### main algorithm of quick sort"]},{"metadata":{"id":"v2_nP14pObAn","colab_type":"code","colab":{}},"cell_type":"code","source":["def quickSort(a, s, e, partition=partition):\n"," # base case , can not be divided further\n"," if s >= e:\n"," return \n"," p = partition(a, s, e)\n"," \n"," # conquer smaller problem\n"," quickSort(a, s , p-1, partition)\n"," quickSort(a, p+1, e, partition)\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"vPtdpJnApa4n","colab_type":"text"},"cell_type":"markdown","source":[""]},{"metadata":{"id":"8N4QPVcqouFf","colab_type":"text"},"cell_type":"markdown","source":["### experiment to see the stability of quick sort"]},{"metadata":{"id":"oOHBweKDgiMw","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":35},"outputId":"1634d771-17cd-4bec-de8d-2da7e3632066","executionInfo":{"status":"ok","timestamp":1550561308432,"user_tz":480,"elapsed":588,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["a = [(5, 1), (7, 1),(3, 1), (2, 1), (5, 2), (6,1), (7, 2), (8, 1), (9, 1), (5, 3), (5, 4)] # the second item represents the index of duplcates\n","def partition_tuple(a, s, e):\n"," '''Lumutos partition'''\n"," p = a[e][0]\n"," i = s - 1\n"," for j in range(s, e): #a[s, e-1]\n"," \n"," if a[j][0] <= p:\n"," i += 1\n"," a[i], a[j] = a[j], a[i] # swap a[i] and a[j]\n"," # print out the range of each region\n","# print('p<->i', [a[x] for x in range(s, i+1)])\n","# print('i+1<->j', [a[x] for x in range(i+1, j+1)])\n"," # place p at position i+1 through swapping with a[i+1]\n"," a[i+1], a[e] = a[e], a[i+1]\n"," return i+1\n","quickSort(a, 0, len(a) - 1, partition_tuple)\n","print(a)"],"execution_count":47,"outputs":[{"output_type":"stream","text":["[(2, 1), (3, 1), (5, 1), (5, 2), (5, 3), (5, 4), (6, 1), (7, 1), (7, 2), (8, 1), (9, 1)]\n"],"name":"stdout"}]},{"metadata":{"id":"QqcdUXaepGSa","colab_type":"text"},"cell_type":"markdown","source":["### experiment to see the performance of worst time"]},{"metadata":{"id":"5n7nsw13pLWr","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":54},"outputId":"736cf200-711d-4f42-b2b1-f5c369f70ce8","executionInfo":{"status":"ok","timestamp":1550562301025,"user_tz":480,"elapsed":637,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["import random, time\n","lst1 = [random.randint(1, 25) for i in range(400)]\n","lst2 = [i for i in range(400)[::-1]]\n","t1 = time.time()\n","quickSort(lst1, 0, len(lst1)-1, partition)\n","print('time for random values:', time.time()-t1)\n","\n","t1 = time.time()\n","quickSort(lst2, 0, len(lst2)-1, partition)\n","print('time for sorted values:', time.time()-t1)"],"execution_count":56,"outputs":[{"output_type":"stream","text":["time for random values: 0.0017516613006591797\n","time for sorted values: 0.0171658992767334\n"],"name":"stdout"}]},{"metadata":{"id":"0y5x07wwo4Um","colab_type":"text"},"cell_type":"markdown","source":["### Hoare Partition"]},{"metadata":{"id":"3vNUigFmo7ei","colab_type":"code","colab":{}},"cell_type":"code","source":["# def partition_hoare(a, s, e):\n","# '''Hoare Parition'''\n","# p = a[e]\n","# i = s\n","# j = e-1\n","# while True:\n","# while a[i] <= p and i < j:\n","# i += 1\n","# while a[j] > p and i < j:\n","# j -= 1\n","# if i < j:\n","# a[i], a[j] = a[j], a[i]\n","# else:\n","# return j\n","# return j"],"execution_count":0,"outputs":[]},{"metadata":{"id":"GKbXRk4Czwjt","colab_type":"code","colab":{"base_uri":"https://localhost:8080/","height":54},"outputId":"be048173-9125-4716-89f0-17ad7fb0b345","executionInfo":{"status":"ok","timestamp":1550564268216,"user_tz":480,"elapsed":325,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}}},"cell_type":"code","source":["# lst = [9, 10, 2, 8, 9, 3, 7]\n","# print(partition_hoare(lst, 0, len(lst)-1))\n","# print(lst)"],"execution_count":72,"outputs":[{"output_type":"stream","text":["2\n","[3, 2, 10, 8, 9, 9, 7]\n"],"name":"stdout"}]},{"metadata":{"id":"4EDqug7Yg2yl","colab_type":"text"},"cell_type":"markdown","source":["## HeapSort in O(nlogn)"]},{"metadata":{"id":"0PE9BxQBg7lu","colab_type":"code","colab":{}},"cell_type":"code","source":["from heapq import heapify, heappop\n","def heapsort(a):\n"," heapify(a)\n"," return [heappop(a) for i in range(len(a))]"],"execution_count":0,"outputs":[]},{"metadata":{"id":"PcUurYvkg_Px","colab_type":"code","outputId":"a96f214c-6fdb-4ed5-9c94-7e8772e65fb5","executionInfo":{"status":"ok","timestamp":1550525399708,"user_tz":480,"elapsed":286,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["lst = [21, 1, 45, 78, 3, 5]\n","heapsort(lst)"],"execution_count":0,"outputs":[{"output_type":"execute_result","data":{"text/plain":["[1, 3, 5, 21, 45, 78]"]},"metadata":{"tags":[]},"execution_count":2}]},{"metadata":{"id":"K1EUj-De16tk","colab_type":"text"},"cell_type":"markdown","source":["## Bucket Sort"]},{"metadata":{"id":"GOF5OoRGioTg","colab_type":"code","colab":{}},"cell_type":"code","source":[""],"execution_count":0,"outputs":[]}]} -------------------------------------------------------------------------------- /Colab Codes/Colab Notebooks/graph_data_structure.ipynb: -------------------------------------------------------------------------------- 1 | {"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"name":"graph_data_structure.ipynb","version":"0.3.2","provenance":[],"collapsed_sections":[],"toc_visible":true},"kernelspec":{"name":"python3","display_name":"Python 3"}},"cells":[{"metadata":{"id":"QqvQdfYqnyIq","colab_type":"text"},"cell_type":"markdown","source":["### Python 2-d array"]},{"metadata":{"id":"GaOxthzYn1vA","colab_type":"code","colab":{}},"cell_type":"code","source":["ta = [[11, 3, 9, 1], [25, 6,10], [10, 8, 12, 5]]"],"execution_count":0,"outputs":[]},{"metadata":{"id":"I7HYxgqMoJUP","colab_type":"code","outputId":"b109f9c0-cf54-47fb-ffdf-a176b0f04b89","executionInfo":{"status":"ok","timestamp":1552498711913,"user_tz":420,"elapsed":4896,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["print(ta[0])\n","print(ta[2][1])"],"execution_count":2,"outputs":[{"output_type":"stream","text":["[11, 3, 9, 1]\n","8\n"],"name":"stdout"}]},{"metadata":{"id":"r8TlWsjzqZ4R","colab_type":"text"},"cell_type":"markdown","source":["#### Empty 2-d array"]},{"metadata":{"id":"MAM2UOQ7qiAN","colab_type":"code","outputId":"e63256a8-7834-4f8c-a07d-2c84eeaf3d5d","executionInfo":{"status":"ok","timestamp":1552498711918,"user_tz":420,"elapsed":4869,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["empty_2d = [[]]\n","print(empty_2d)"],"execution_count":3,"outputs":[{"output_type":"stream","text":["[[]]\n"],"name":"stdout"}]},{"metadata":{"id":"3BoPkppMqo3V","colab_type":"text"},"cell_type":"markdown","source":["#### fix the outer dimension"]},{"metadata":{"id":"LBMKQA59qv8E","colab_type":"code","outputId":"99575bde-cfaa-4f8d-edf7-10d2f71d374e","executionInfo":{"status":"ok","timestamp":1552498711924,"user_tz":420,"elapsed":4852,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["fix_out_d = [[] for _ in range(5)]\n","print(fix_out_d)"],"execution_count":4,"outputs":[{"output_type":"stream","text":["[[], [], [], [], []]\n"],"name":"stdout"}]},{"metadata":{"id":"_GtKfbeRtnIo","colab_type":"text"},"cell_type":"markdown","source":["#### matrices"]},{"metadata":{"id":"PCR24OxUto-Z","colab_type":"code","outputId":"495a315c-e171-4068-f183-310a64a25ec6","executionInfo":{"status":"ok","timestamp":1552498711929,"user_tz":420,"elapsed":4839,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["rows, cols = 3, 4\n","m1 = [[0 for _ in range(cols)] for _ in range(rows)] # rows * cols\n","m2 = [[0]*cols for _ in range(rows)] # rows * cols\n","print(m1, m2)"],"execution_count":5,"outputs":[{"output_type":"stream","text":["[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]\n"],"name":"stdout"}]},{"metadata":{"id":"2bzn_EbNuWrt","colab_type":"code","outputId":"f190b0f1-d8e8-4967-ef48-b4bc5b3f9716","executionInfo":{"status":"ok","timestamp":1552498711932,"user_tz":420,"elapsed":4825,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["m1[1][2] = 1\n","m2[1][2] = 1\n","print(m1, m2)"],"execution_count":6,"outputs":[{"output_type":"stream","text":["[[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]] [[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]\n"],"name":"stdout"}]},{"metadata":{"id":"bILW8JA1vRG0","colab_type":"code","outputId":"3308eee8-202a-405c-fa4b-9aef3f70f9f3","executionInfo":{"status":"ok","timestamp":1552498711935,"user_tz":420,"elapsed":4813,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["m4 = [[0]*cols]*rows\n","m4[1][2] = 1\n","print(m4)"],"execution_count":7,"outputs":[{"output_type":"stream","text":["[[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]\n"],"name":"stdout"}]},{"metadata":{"id":"l6jRaJGuwKiK","colab_type":"text"},"cell_type":"markdown","source":["#### access rows"]},{"metadata":{"id":"o1MWJZtOwMUr","colab_type":"code","outputId":"5637c2c6-776d-4c31-a697-532e65b5a8cb","executionInfo":{"status":"ok","timestamp":1552498711937,"user_tz":420,"elapsed":4798,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":72}},"cell_type":"code","source":["for row in m1:\n"," print(row)"],"execution_count":8,"outputs":[{"output_type":"stream","text":["[0, 0, 0, 0]\n","[0, 0, 1, 0]\n","[0, 0, 0, 0]\n"],"name":"stdout"}]},{"metadata":{"id":"nuwXftOcw4G0","colab_type":"text"},"cell_type":"markdown","source":["#### access cols"]},{"metadata":{"id":"2JZVSYv_w5yn","colab_type":"code","outputId":"e3b76e39-3260-458f-8906-c3acc9aee004","executionInfo":{"status":"ok","timestamp":1552498711939,"user_tz":420,"elapsed":4785,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":90}},"cell_type":"code","source":["for i in range(cols):\n"," col = [row[i] for row in m1]\n"," print(col)"],"execution_count":9,"outputs":[{"output_type":"stream","text":["[0, 0, 0]\n","[0, 0, 0]\n","[0, 1, 0]\n","[0, 0, 0]\n"],"name":"stdout"}]},{"metadata":{"id":"OUtscU8nxZMY","colab_type":"code","outputId":"8438deaa-00f7-4c85-f39d-af4fb9b91ca8","executionInfo":{"status":"ok","timestamp":1552498711946,"user_tz":420,"elapsed":4778,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["transposedM1 = list(zip(*m1))\n","print(transposedM1)"],"execution_count":10,"outputs":[{"output_type":"stream","text":["[(0, 0, 0), (0, 0, 0), (0, 1, 0), (0, 0, 0)]\n"],"name":"stdout"}]},{"metadata":{"id":"fmVFH68bbFi6","colab_type":"text"},"cell_type":"markdown","source":["### adjacency matrix"]},{"metadata":{"id":"60craYL7bIC_","colab_type":"code","outputId":"b96ceee6-7b8b-4bee-8473-babc442774e2","executionInfo":{"status":"ok","timestamp":1552498711949,"user_tz":420,"elapsed":4762,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["am = [[0]*7 for _ in range(7)]\n","\n","# set 8 edges\n","am[0][1] = am[1][0] = 1\n","am[0][2] = am[2][0] = 1\n","am[1][2] = am[2][1] = 1\n","am[1][3] = am[3][1] = 1\n","am[2][4] = am[4][2] = 1\n","am[3][4] = am[4][3] = 1\n","am[4][5] = am[5][4] = 1\n","am[5][6] = am[6][5] = 1\n","\n","print(am)"],"execution_count":11,"outputs":[{"output_type":"stream","text":["[[0, 1, 1, 0, 0, 0, 0], [1, 0, 1, 1, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0], [0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, 0]]\n"],"name":"stdout"}]},{"metadata":{"id":"Bbh2mPsUdhzm","colab_type":"text"},"cell_type":"markdown","source":["### adjacency list"]},{"metadata":{"id":"nfeVyXxadkJM","colab_type":"code","outputId":"da19e829-0800-4bec-f563-5a48459cd27e","executionInfo":{"status":"ok","timestamp":1552498711954,"user_tz":420,"elapsed":4749,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["al = [[] for _ in range(7)]\n","\n","# set 8 edges\n","al[0] = [1, 2]\n","al[1] = [2, 3]\n","al[2] = [0, 4]\n","al[3] = [1, 4]\n","al[4] = [2, 3, 5]\n","al[5] = [4, 6]\n","al[6] = [5]\n","\n","print(al)"],"execution_count":12,"outputs":[{"output_type":"stream","text":["[[1, 2], [2, 3], [0, 4], [1, 4], [2, 3, 5], [4, 6], [5]]\n"],"name":"stdout"}]},{"metadata":{"id":"pc6flSew8FXi","colab_type":"text"},"cell_type":"markdown","source":["### edge list"]},{"metadata":{"id":"LKJ3ch4s8G3x","colab_type":"code","outputId":"8b38471b-d9eb-4b8a-c37a-43bb61474da6","executionInfo":{"status":"ok","timestamp":1552498711957,"user_tz":420,"elapsed":4735,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["el = []\n","el.extend([[0, 1], [1, 0]])\n","el.extend([[0, 2], [2, 0]])\n","el.extend([[1, 2], [2, 1]])\n","el.extend([[1, 3], [3, 1]])\n","el.extend([[3, 4], [4, 3]])\n","el.extend([[2, 4], [4, 2]])\n","el.extend([[4, 5], [5, 4]])\n","el.extend([[5, 6], [6, 5]])\n","\n","print(el)"],"execution_count":13,"outputs":[{"output_type":"stream","text":["[[0, 1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1], [1, 3], [3, 1], [3, 4], [4, 3], [2, 4], [4, 2], [4, 5], [5, 4], [5, 6], [6, 5]]\n"],"name":"stdout"}]},{"metadata":{"id":"YFtL16Ko2OaU","colab_type":"text"},"cell_type":"markdown","source":["### Use dictionary data structure"]},{"metadata":{"id":"lLL_GR0L2R7U","colab_type":"code","outputId":"d9f7163c-3927-49b5-86c3-73c814ae1880","executionInfo":{"status":"ok","timestamp":1552498711958,"user_tz":420,"elapsed":4722,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["from collections import defaultdict\n","\n","d = defaultdict(set)\n","for v1, v2 in el:\n"," d[chr(v1 + ord('a'))].add(chr(v2 + ord('a')))\n","\n","print(d)"],"execution_count":14,"outputs":[{"output_type":"stream","text":["defaultdict(, {'a': {'c', 'b'}, 'b': {'a', 'd', 'c'}, 'c': {'a', 'e', 'b'}, 'd': {'e', 'b'}, 'e': {'d', 'f', 'c'}, 'f': {'e', 'g'}, 'g': {'f'}})\n"],"name":"stdout"}]},{"metadata":{"id":"R8_0w0qR3ilj","colab_type":"code","outputId":"1e1bf46f-94ee-4110-d63c-95ce6767e292","executionInfo":{"status":"ok","timestamp":1552498711963,"user_tz":420,"elapsed":4712,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["dw = defaultdict(dict)\n","for v1, v2 in el:\n"," dw[v1][v2] = v1 + v2\n","print(dw)"],"execution_count":15,"outputs":[{"output_type":"stream","text":["defaultdict(, {0: {1: 1, 2: 2}, 1: {0: 1, 2: 3, 3: 4}, 2: {0: 2, 1: 3, 4: 6}, 3: {1: 4, 4: 7}, 4: {3: 7, 2: 6, 5: 9}, 5: {4: 9, 6: 11}, 6: {5: 11}})\n"],"name":"stdout"}]},{"metadata":{"id":"b_55IC6F8iP_","colab_type":"text"},"cell_type":"markdown","source":["# Breath-first Search"]},{"metadata":{"id":"b_Bo_1as8kX1","colab_type":"code","colab":{}},"cell_type":"code","source":["class STATE:\n"," white = 0\n"," gray = 1\n"," black = 2\n"," \n","def bfs(g, s):\n"," '''node by node bfs using queue''' \n"," v = len(g)\n"," state = [False] * v\n"," \n"," # allocate space for the predecessor list and colors \n"," pi = [None] * v\n"," state[s] = True # make the state of the visiting node\n"," dist = [0] * v\n"," \n"," q, orders = [s], [s]\n"," while q:\n"," u = q.pop(0)\n"," \n"," print(u, ' out, ', end = ' ')\n"," for v in g[u]:\n"," if not state[v]:\n"," state[v] = True\n"," pi[v] = u # set the predecessor\n"," dist[v] = dist[u] + 1\n"," q.append(v)\n"," orders.append(v)\n"," print(v, ' in', end = ' ')\n"," return orders, pi, dist\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"meQvv4lE_X27","colab_type":"code","outputId":"0a4875f0-c2ad-4d1a-c869-6a9026221ba9","executionInfo":{"status":"ok","timestamp":1552498711969,"user_tz":420,"elapsed":4697,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["orders, pi, dist = bfs(al, 0)"],"execution_count":17,"outputs":[{"output_type":"stream","text":["0 out, 1 in 2 in 1 out, 3 in 2 out, 4 in 3 out, 4 out, 5 in 5 out, 6 in 6 out, "],"name":"stdout"}]},{"metadata":{"id":"TEZR7eayuZuI","colab_type":"code","outputId":"801c3c94-75f5-4b89-d578-69d262d29c68","executionInfo":{"status":"ok","timestamp":1552498711971,"user_tz":420,"elapsed":4685,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["print(pi)"],"execution_count":18,"outputs":[{"output_type":"stream","text":["[None, 0, 0, 1, 2, 4, 5]\n"],"name":"stdout"}]},{"metadata":{"id":"CoGfQZk1BmqD","colab_type":"code","colab":{}},"cell_type":"code","source":["def get_path(s, t, pi):\n"," '''iterative'''\n"," p = t\n"," path = []\n"," while p != s:\n"," path.append(p)\n"," p = pi[p]\n"," path.append(s)\n"," return path[::-1]\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"XqYMGN4nCBJA","colab_type":"code","outputId":"8a7e1a63-7409-4c37-f80c-a3ba5a7d58b2","executionInfo":{"status":"ok","timestamp":1552498711982,"user_tz":420,"elapsed":4676,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["get_path(0, 5, pi)"],"execution_count":20,"outputs":[{"output_type":"execute_result","data":{"text/plain":["[0, 2, 4, 5]"]},"metadata":{"tags":[]},"execution_count":20}]},{"metadata":{"id":"wmejAVv8s-ZV","colab_type":"code","colab":{}},"cell_type":"code","source":["def get_path(s, t, pi, path):\n"," '''recursive'''\n"," if s == t:\n"," path.append(t)\n"," return\n"," elif pi[t] is None:\n"," print('no path from ', s, ' to ', v)\n"," else:\n"," get_path(s, pi[t], pi, path)\n"," path.append(t)\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"4aUNsrKPtkG6","colab_type":"code","outputId":"940a2f48-7d81-4dcd-e24a-0128271c5263","executionInfo":{"status":"ok","timestamp":1552498711988,"user_tz":420,"elapsed":4663,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["path = []\n","get_path(0, 5, pi, path)\n","print(path)"],"execution_count":22,"outputs":[{"output_type":"stream","text":["[0, 2, 4, 5]\n"],"name":"stdout"}]},{"metadata":{"id":"aR60hTwOQOo0","colab_type":"code","colab":{}},"cell_type":"code","source":["def bfs(g, s):\n"," '''simplified bfs'''\n"," v = len(g)\n"," colors = [STATE.white] * v\n"," \n"," q, orders = [s], [s]\n"," complete_orders = []\n"," colors[s] = STATE.gray # make the state of the visiting node\n"," while q:\n"," u = q.pop(0)\n"," \n"," for v in g[u]:\n"," if colors[v] == STATE.white:\n"," colors[v] = STATE.gray\n"," q.append(v)\n"," orders.append(v)\n"," # complete \n"," colors[u] = STATE.black\n"," complete_orders.append(u)\n"," return orders, complete_orders"],"execution_count":0,"outputs":[]},{"metadata":{"id":"CN9MaYWwQ5vb","colab_type":"code","outputId":"4ddf5a46-d062-40ef-8ebe-804bb6467cb2","executionInfo":{"status":"ok","timestamp":1552498711998,"user_tz":420,"elapsed":4658,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["print(bfs(al, 0))"],"execution_count":24,"outputs":[{"output_type":"stream","text":["([0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6])\n"],"name":"stdout"}]},{"metadata":{"id":"I-LT_HgDrrtI","colab_type":"text"},"cell_type":"markdown","source":["#### level by level bfs"]},{"metadata":{"id":"sQyW-n5qrt6k","colab_type":"code","colab":{}},"cell_type":"code","source":["def bfs_level(g, s):\n"," '''level by level bfs'''\n"," v = len(g)\n"," state = [False] * v\n"," \n"," orders = []\n"," lst = [s]\n"," state[s] = True\n"," d = 0 # track distance\n"," while lst:\n"," print('distance ', d, ': ', lst)\n"," tmp_lst = []\n"," for u in lst:\n"," orders.append(u)\n"," for v in g[u]:\n"," if not state[v]:\n"," state[v] = True\n"," tmp_lst.append(v) \n"," lst = tmp_lst\n"," d += 1\n"," return orders\n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"KwUfwlRN2qbe","colab_type":"code","outputId":"79c23a32-db70-483b-db81-3ee958fea037","executionInfo":{"status":"ok","timestamp":1552498712006,"user_tz":420,"elapsed":4646,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":127}},"cell_type":"code","source":["print(bfs_level(al, 0))"],"execution_count":26,"outputs":[{"output_type":"stream","text":["distance 0 : [0]\n","distance 1 : [1, 2]\n","distance 2 : [3, 4]\n","distance 3 : [5]\n","distance 4 : [6]\n","[0, 1, 2, 3, 4, 5, 6]\n"],"name":"stdout"}]},{"metadata":{"id":"KDFDgG-BOBml","colab_type":"text"},"cell_type":"markdown","source":["# Depth-first Search"]},{"metadata":{"id":"TAPb-16WOHMI","colab_type":"code","colab":{}},"cell_type":"code","source":["def dfs(g, s, colors, orders, complete_orders):\n"," colors[s] = STATE.gray\n"," orders.append(s)\n"," for v in g[s]:\n"," if colors[v] == STATE.white:\n"," dfs(g, v, colors, orders, complete_orders)\n"," # complete\n"," colors[s] = STATE.black # this is not necessary in the code, just to help track the state\n"," complete_orders.append(s)\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"IdRqJxJ34qkw","colab_type":"code","outputId":"45757452-267b-41e1-dfa0-c45cc2c95f01","executionInfo":{"status":"ok","timestamp":1552498712011,"user_tz":420,"elapsed":4634,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["# initialization\n","'''start from 0'''\n","v = len(al)\n","orders, complete_orders = [], []\n","colors = [STATE.white] * v\n","dfs(al,0, colors, orders, complete_orders)\n","\n","print(orders, complete_orders)"],"execution_count":28,"outputs":[{"output_type":"stream","text":["[0, 1, 2, 4, 3, 5, 6] [3, 6, 5, 4, 2, 1, 0]\n"],"name":"stdout"}]},{"metadata":{"id":"FNElkf4jmOre","colab_type":"code","outputId":"8dda9d1d-d4da-429a-ac9d-92b56ec3a8f1","executionInfo":{"status":"ok","timestamp":1552498712013,"user_tz":420,"elapsed":4624,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["# initialization\n","'''start from 1'''\n","v = len(al)\n","orders, complete_orders = [], []\n","colors = [STATE.white] * v\n","dfs(al,1, colors, orders, complete_orders)\n","\n","print(orders, complete_orders)"],"execution_count":29,"outputs":[{"output_type":"stream","text":["[1, 2, 0, 4, 3, 5, 6] [0, 3, 6, 5, 4, 2, 1]\n"],"name":"stdout"}]},{"metadata":{"id":"H_5VwJiLqca6","colab_type":"code","colab":{}},"cell_type":"code","source":["def dftIter(g, s):\n"," '''not preserving the same discovery ordering'''\n"," n = len(g)\n"," orders = []\n"," colors = [STATE.white] * n\n"," stack = [s]\n","\n"," orders.append(s) # track gray order\n"," colors[s] = STATE.gray\n"," \n"," while stack:\n"," u = stack.pop()\n"," \n"," for v in g[u]:\n"," if colors[v] == STATE.white:\n"," colors[v] = STATE.gray\n"," stack.append(v)\n"," orders.append(v) # track gray order\n"," \n"," return orders"],"execution_count":0,"outputs":[]},{"metadata":{"id":"q3hq9ARKqqnw","colab_type":"code","outputId":"6644b5fb-752c-48da-cee3-d617a576f501","executionInfo":{"status":"ok","timestamp":1552498712018,"user_tz":420,"elapsed":4608,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["# initialization\n","'''start from 0'''\n","print(dftIter(al,0))"],"execution_count":31,"outputs":[{"output_type":"stream","text":["[0, 1, 2, 4, 3, 5, 6]\n"],"name":"stdout"}]},{"metadata":{"id":"RIVOD221rHii","colab_type":"code","outputId":"cca27f41-bbc6-4f99-8584-c82ef53df5cc","executionInfo":{"status":"ok","timestamp":1552498712021,"user_tz":420,"elapsed":4596,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["print(dftIter(al, 1))"],"execution_count":32,"outputs":[{"output_type":"stream","text":["[1, 2, 3, 4, 5, 6, 0]\n"],"name":"stdout"}]},{"metadata":{"id":"I4eVWYzGj01U","colab_type":"code","colab":{}},"cell_type":"code","source":["def dftIter(g, s):\n"," '''preserving only discovery ordering'''\n"," n = len(g)\n"," orders = []\n"," colors = [STATE.white] * n\n"," stack = [s]\n","\n"," #orders.append(s) # track gray order\n"," #colors[s] = STATE.gray\n"," \n"," while stack:\n"," u = stack.pop()\n"," if colors[u] == STATE.white:\n"," orders.append(u) # track gray order\n"," colors[u] = STATE.gray\n"," for v in g[u][::-1]:\n"," if colors[v] == STATE.white:\n"," \n"," stack.append(v)\n"," #orders.append(v) # track gray order\n"," \n"," return orders"],"execution_count":0,"outputs":[]},{"metadata":{"id":"5JWNwi9rlAER","colab_type":"code","outputId":"b1131559-e0a3-49e6-837b-440d34c01ba3","executionInfo":{"status":"ok","timestamp":1552498712036,"user_tz":420,"elapsed":4596,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["print(dftIter(al, 0))"],"execution_count":34,"outputs":[{"output_type":"stream","text":["[0, 1, 2, 4, 3, 5, 6]\n"],"name":"stdout"}]},{"metadata":{"id":"mBqP-iy9ma3d","colab_type":"code","outputId":"2dab6dff-4fdc-4a44-ec2b-1dee60d0bb06","executionInfo":{"status":"ok","timestamp":1552498712043,"user_tz":420,"elapsed":4588,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["print(dftIter(al, 1))"],"execution_count":35,"outputs":[{"output_type":"stream","text":["[1, 2, 0, 4, 3, 5, 6]\n"],"name":"stdout"}]},{"metadata":{"id":"rrFl2gwokZON","colab_type":"code","colab":{}},"cell_type":"code","source":["def dfsIter(g, s):\n"," '''iterative dfs'''\n"," v = len(g)\n"," orders, complete_orders = [], []\n"," colors = [STATE.white] * v\n"," stack = [s]\n","\n"," orders.append(s) # track gray order\n"," colors[s] = STATE.gray\n"," \n"," while stack:\n"," u = stack[-1]\n"," bAdj = False\n"," for v in g[u]:\n"," if colors[v] == STATE.white:\n"," colors[v] = STATE.gray\n"," stack.append(v)\n"," orders.append(v) # track gray order\n"," bAdj = True\n"," break\n"," \n"," if not bAdj: # if no adjacent is found, pop out\n"," # complete\n"," colors[u] = STATE.black # this is not necessary in the code, just to help track the state\n"," complete_orders.append(u)\n"," stack.pop()\n"," \n"," return orders, complete_orders\n"," \n","\n"," \n"," "],"execution_count":0,"outputs":[]},{"metadata":{"id":"vGaO1vCbly-a","colab_type":"code","outputId":"c32c9589-3d7c-46d7-dd2c-546cfcc04393","executionInfo":{"status":"ok","timestamp":1552498712054,"user_tz":420,"elapsed":4587,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":35}},"cell_type":"code","source":["print(dfsIter(al, 0))"],"execution_count":37,"outputs":[{"output_type":"stream","text":["([0, 1, 2, 4, 3, 5, 6], [3, 6, 5, 4, 2, 1, 0])\n"],"name":"stdout"}]},{"metadata":{"id":"wo9AyzN4tRSw","colab_type":"text"},"cell_type":"markdown","source":["### To do\n","Implement the simple iterative version that track the discover and finishing time. So that we can use the iterative version in the topological sort and strongly connected component."]},{"metadata":{"id":"RlYFKGBrfxLo","colab_type":"text"},"cell_type":"markdown","source":["### add finish time"]},{"metadata":{"id":"12yqIv0pf38y","colab_type":"code","colab":{}},"cell_type":"code","source":["# def static_var(varname, value):\n","# def decorate(func):\n","# setattr(func, varname, value)\n","# return func\n","# return decorate\n","# @static_var(\"t\", -1)\n","def dfs(g, s, colors, dt, ft):\n"," dfs.t += 1 # static variable\n"," colors[s] = STATE.gray\n"," dt[s] = dfs.t\n"," for v in g[s]:\n"," if colors[v] == STATE.white:\n"," dfs(g, v, colors, dt, ft)\n"," # complete\n"," dfs.t += 1\n"," ft[s] = dfs.t\n"," return"],"execution_count":0,"outputs":[]},{"metadata":{"id":"WKM_eo7ngKsG","colab_type":"code","outputId":"b2955e44-33bf-4a8c-8e7c-d35198fbfdb0","executionInfo":{"status":"ok","timestamp":1552498712061,"user_tz":420,"elapsed":4578,"user":{"displayName":"Li Yin","photoUrl":"https://lh5.googleusercontent.com/-KgiTKdqPRUg/AAAAAAAAAAI/AAAAAAAAAIE/aHQ6xO5vQpY/s64/photo.jpg","userId":"13365523799853678553"}},"colab":{"base_uri":"https://localhost:8080/","height":54}},"cell_type":"code","source":["# initialization\n","v = len(al)\n","dt, ft = [-1] * v, [-1] * v\n","colors = [STATE.white] * v\n","dfs.t = -1\n","dfs(al,0, colors, dt, ft)\n","\n","merge_orders = [-1] * 2 * v\n","\n","for i, t in enumerate(dt):\n"," merge_orders[t] = i\n"," \n","for i, t in enumerate(ft):\n"," merge_orders[t] = i\n","\n","print(merge_orders)\n","nodes = set()\n","for i in merge_orders:\n"," if i not in nodes:\n"," print('(', i, end = ', ')\n"," nodes.add(i)\n"," else:\n"," print(i, ') ', end = ' ')\n"],"execution_count":39,"outputs":[{"output_type":"stream","text":["[0, 1, 2, 4, 3, 3, 5, 6, 6, 5, 4, 2, 1, 0]\n","( 0, ( 1, ( 2, ( 4, ( 3, 3 ) ( 5, ( 6, 6 ) 5 ) 4 ) 2 ) 1 ) 0 ) "],"name":"stdout"}]}]} -------------------------------------------------------------------------------- /Advanced_Search_on_Linear_Data_Structures.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Advanced Search on Linear Data Structures.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [], 9 | "toc_visible": true 10 | }, 11 | "kernelspec": { 12 | "name": "python3", 13 | "display_name": "Python 3" 14 | } 15 | }, 16 | "cells": [ 17 | { 18 | "cell_type": "markdown", 19 | "metadata": { 20 | "id": "p1AUD30cnI0b", 21 | "colab_type": "text" 22 | }, 23 | "source": [ 24 | "# Slow-fast Pointers" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": { 30 | "id": "uxNIaguAv2QT", 31 | "colab_type": "text" 32 | }, 33 | "source": [ 34 | "## Array" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": { 40 | "id": "Kz8-B6bTed1u", 41 | "colab_type": "text" 42 | }, 43 | "source": [ 44 | "### Remove duplicates" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "metadata": { 50 | "id": "P6YqRE57ebXz", 51 | "colab_type": "code", 52 | "colab": {} 53 | }, 54 | "source": [ 55 | "a = [0,0,1,1,1,2,2,3,3,4]" 56 | ], 57 | "execution_count": 0, 58 | "outputs": [] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "metadata": { 63 | "id": "2a-xbM6GesgQ", 64 | "colab_type": "code", 65 | "colab": {} 66 | }, 67 | "source": [ 68 | "def removeDuplicates(nums) -> int:\n", 69 | " i, j = 0, 0\n", 70 | " while j < len(nums):\n", 71 | " print('[0, i]:', nums[0:i+1], '[i+1, j]:', nums[i+1:j+1])\n", 72 | " if nums[i] != nums[j]:\n", 73 | " # Copy j to i+1\n", 74 | " i += 1\n", 75 | " nums[i] = nums[j]\n", 76 | " print('copy value {} at index {} to index {}'.format(nums[j],j, i))\n", 77 | " j += 1\n", 78 | " return i + 1" 79 | ], 80 | "execution_count": 0, 81 | "outputs": [] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "metadata": { 86 | "id": "9WPUvQCge_IW", 87 | "colab_type": "code", 88 | "outputId": "ea817fac-5cdc-4514-90ea-f709f273cb15", 89 | "colab": { 90 | "base_uri": "https://localhost:8080/", 91 | "height": 293 92 | } 93 | }, 94 | "source": [ 95 | "# Test\n", 96 | "removeDuplicates(a)\n", 97 | "a" 98 | ], 99 | "execution_count": 0, 100 | "outputs": [ 101 | { 102 | "output_type": "stream", 103 | "text": [ 104 | "[0, i]: [0] [i+1, j]: []\n", 105 | "[0, i]: [0] [i+1, j]: [0]\n", 106 | "[0, i]: [0] [i+1, j]: [0, 1]\n", 107 | "copy value 1 at index 2 to index 1\n", 108 | "[0, i]: [0, 1] [i+1, j]: [1, 1]\n", 109 | "[0, i]: [0, 1] [i+1, j]: [1, 1, 1]\n", 110 | "[0, i]: [0, 1] [i+1, j]: [1, 1, 1, 2]\n", 111 | "copy value 2 at index 5 to index 2\n", 112 | "[0, i]: [0, 1, 2] [i+1, j]: [1, 1, 2, 2]\n", 113 | "[0, i]: [0, 1, 2] [i+1, j]: [1, 1, 2, 2, 3]\n", 114 | "copy value 3 at index 7 to index 3\n", 115 | "[0, i]: [0, 1, 2, 3] [i+1, j]: [1, 2, 2, 3, 3]\n", 116 | "[0, i]: [0, 1, 2, 3] [i+1, j]: [1, 2, 2, 3, 3, 4]\n", 117 | "copy value 4 at index 9 to index 4\n" 118 | ], 119 | "name": "stdout" 120 | }, 121 | { 122 | "output_type": "execute_result", 123 | "data": { 124 | "text/plain": [ 125 | "[0, 1, 2, 3, 4, 2, 2, 3, 3, 4]" 126 | ] 127 | }, 128 | "metadata": { 129 | "tags": [] 130 | }, 131 | "execution_count": 32 132 | } 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": { 138 | "id": "WpoPXLowYthf", 139 | "colab_type": "text" 140 | }, 141 | "source": [ 142 | "### Minimum Size Subarray Sum" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "metadata": { 148 | "id": "y_Kq77AwYuCx", 149 | "colab_type": "code", 150 | "colab": {} 151 | }, 152 | "source": [ 153 | "def minSubArrayLen(s: int, nums) -> int:\n", 154 | " i, j = 0, 0\n", 155 | " acc = 0\n", 156 | " ans = float('inf')\n", 157 | " while j < len(nums):\n", 158 | " acc += nums[j]\n", 159 | " # Shrink the window\n", 160 | " while acc >= s:\n", 161 | " ans = min(ans, j - i + 1)\n", 162 | " acc -= nums[i]\n", 163 | " i += 1\n", 164 | " j += 1\n", 165 | " \n", 166 | " return ans if ans < float('inf') else 0" 167 | ], 168 | "execution_count": 0, 169 | "outputs": [] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "metadata": { 174 | "id": "9gwIePmuY9ZR", 175 | "colab_type": "code", 176 | "outputId": "76fdcc30-1225-4724-d4b4-cb0c3ed4d1e7", 177 | "colab": { 178 | "base_uri": "https://localhost:8080/", 179 | "height": 35 180 | } 181 | }, 182 | "source": [ 183 | "s = 7\n", 184 | "nums = [1,4,1,2,4,3]\n", 185 | "minSubArrayLen(s, nums)" 186 | ], 187 | "execution_count": 0, 188 | "outputs": [ 189 | { 190 | "output_type": "execute_result", 191 | "data": { 192 | "text/plain": [ 193 | "2" 194 | ] 195 | }, 196 | "metadata": { 197 | "tags": [] 198 | }, 199 | "execution_count": 34 200 | } 201 | ] 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "metadata": { 206 | "id": "7Tvt4n4qHZxP", 207 | "colab_type": "text" 208 | }, 209 | "source": [ 210 | "### [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "metadata": { 216 | "id": "JfSUte9NHbF5", 217 | "colab_type": "code", 218 | "colab": {} 219 | }, 220 | "source": [ 221 | "S = \"ADOBECODEBANC\"\n", 222 | "T = \"ABC\"" 223 | ], 224 | "execution_count": 0, 225 | "outputs": [] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "metadata": { 230 | "id": "v2aQ3SfaHrdo", 231 | "colab_type": "code", 232 | "colab": {} 233 | }, 234 | "source": [ 235 | "from collections import Counter\n", 236 | "def minWindow(s, t):\n", 237 | " dict_t = Counter(t)\n", 238 | " count = len(dict_t)\n", 239 | " i, j = 0, 0\n", 240 | " ans = []\n", 241 | " minLen = float('inf')\n", 242 | " while j < len(s):\n", 243 | " c = s[j]\n", 244 | " if c in dict_t:\n", 245 | " dict_t[c] -= 1\n", 246 | " if dict_t[c] == 0:\n", 247 | " count -= 1\n", 248 | " # Shrink the window\n", 249 | " while count == 0 and i < j:\n", 250 | " curLen = j - i + 1\n", 251 | " if curLen < minLen:\n", 252 | " minLen = j - i + 1\n", 253 | " ans = [s[i:j+1]]\n", 254 | " elif curLen == minLen: \n", 255 | " ans.append(s[i:j+1])\n", 256 | "\n", 257 | " c = s[i]\n", 258 | " if c in dict_t:\n", 259 | " dict_t[c] += 1\n", 260 | " if dict_t[c] == 1:\n", 261 | " count += 1\n", 262 | " i += 1\n", 263 | "\n", 264 | " j += 1\n", 265 | " return ans" 266 | ], 267 | "execution_count": 0, 268 | "outputs": [] 269 | }, 270 | { 271 | "cell_type": "code", 272 | "metadata": { 273 | "id": "SrF6tS5PVT6J", 274 | "colab_type": "code", 275 | "colab": { 276 | "base_uri": "https://localhost:8080/", 277 | "height": 35 278 | }, 279 | "outputId": "1b43cf78-a9fe-4a9a-f410-9f44e45d532a" 280 | }, 281 | "source": [ 282 | "S = 'AOBECDBANC'\n", 283 | "minWindow(S, T)" 284 | ], 285 | "execution_count": 6, 286 | "outputs": [ 287 | { 288 | "output_type": "execute_result", 289 | "data": { 290 | "text/plain": [ 291 | "['CDBA', 'BANC']" 292 | ] 293 | }, 294 | "metadata": { 295 | "tags": [] 296 | }, 297 | "execution_count": 6 298 | } 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "metadata": { 304 | "id": "PGsA-6rbv0F_", 305 | "colab_type": "text" 306 | }, 307 | "source": [ 308 | "## Linked List" 309 | ] 310 | }, 311 | { 312 | "cell_type": "markdown", 313 | "metadata": { 314 | "id": "x1TiIhmgv1WR", 315 | "colab_type": "text" 316 | }, 317 | "source": [ 318 | "### Middle of the Linked List" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "metadata": { 324 | "id": "QBa-8mmewBC6", 325 | "colab_type": "code", 326 | "colab": {} 327 | }, 328 | "source": [ 329 | "def middleNode(head):\n", 330 | " slow = fast = head\n", 331 | " while fast and fast.next: \n", 332 | " fast = fast.next.next\n", 333 | " slow = slow.next \n", 334 | " return slow" 335 | ], 336 | "execution_count": 0, 337 | "outputs": [] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "metadata": { 342 | "id": "vAGAFdIIwHLf", 343 | "colab_type": "code", 344 | "colab": {} 345 | }, 346 | "source": [ 347 | "from collections import defaultdict\n", 348 | "class Node:\n", 349 | " def __init__(self, val, next = None):\n", 350 | " self.val = val\n", 351 | " self.next = next\n", 352 | "\n", 353 | "def getLinkedList(val_lst):\n", 354 | " head = cur = None\n", 355 | " # Use a dictionary to track nodes\n", 356 | " Nodes = defaultdict(Node)\n", 357 | " if val_lst:\n", 358 | " head = cur = Node(val_lst[0]) \n", 359 | " Nodes[val_lst[0]] = head \n", 360 | " if len(val_lst) >= 2:\n", 361 | " for i in range(1, len(val_lst)):\n", 362 | " if val_lst[i] not in Nodes:\n", 363 | " cur.next = Node(val_lst[i])\n", 364 | " Nodes[val_lst[i]] = cur.next\n", 365 | " else:\n", 366 | " cur.next = Nodes[val_lst[i]]\n", 367 | " cur = cur.next\n", 368 | " return head\n" 369 | ], 370 | "execution_count": 0, 371 | "outputs": [] 372 | }, 373 | { 374 | "cell_type": "code", 375 | "metadata": { 376 | "id": "22Ajd39uwWDE", 377 | "colab_type": "code", 378 | "outputId": "bf59fd8d-b303-411c-f257-d546652fc2e2", 379 | "colab": { 380 | "base_uri": "https://localhost:8080/", 381 | "height": 35 382 | } 383 | }, 384 | "source": [ 385 | "head1 = getLinkedList([1, 2, 3, 4, 5])\n", 386 | "head2 = getLinkedList([1, 2, 3, 4, 5, 6])\n", 387 | "print(middleNode(head1).val, middleNode(head2).val)" 388 | ], 389 | "execution_count": 0, 390 | "outputs": [ 391 | { 392 | "output_type": "stream", 393 | "text": [ 394 | "3 4\n" 395 | ], 396 | "name": "stdout" 397 | } 398 | ] 399 | }, 400 | { 401 | "cell_type": "markdown", 402 | "metadata": { 403 | "id": "2W37Ktyny09T", 404 | "colab_type": "text" 405 | }, 406 | "source": [ 407 | "### Floyd's Cycle Detection" 408 | ] 409 | }, 410 | { 411 | "cell_type": "code", 412 | "metadata": { 413 | "id": "RVMKzZD_y4HK", 414 | "colab_type": "code", 415 | "colab": {} 416 | }, 417 | "source": [ 418 | "head_cycle = getLinkedList([1, 2, 3, 4, 5, 6, 3])" 419 | ], 420 | "execution_count": 0, 421 | "outputs": [] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "metadata": { 426 | "id": "UEeG5uoxy-ET", 427 | "colab_type": "code", 428 | "colab": {} 429 | }, 430 | "source": [ 431 | "# Looping over a cyclic linked list makes the program stuck \n", 432 | "def iterate(head):\n", 433 | " cur = head_cycle\n", 434 | " while cur:\n", 435 | " print(cur.val)\n", 436 | " cur = cur.next" 437 | ], 438 | "execution_count": 0, 439 | "outputs": [] 440 | }, 441 | { 442 | "cell_type": "markdown", 443 | "metadata": { 444 | "id": "N9GnJe54APNW", 445 | "colab_type": "text" 446 | }, 447 | "source": [ 448 | "### [Check the existence of cycles](https://leetcode.com/problems/linked-list-cycle/)" 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "metadata": { 454 | "id": "EqAIbFI6_5zf", 455 | "colab_type": "code", 456 | "colab": {} 457 | }, 458 | "source": [ 459 | "def hasCycle(head):\n", 460 | " slow = fast = head\n", 461 | " while fast and fast.next:\n", 462 | " slow = slow.next\n", 463 | " fast = fast.next.next\n", 464 | " if slow == fast:\n", 465 | " return True\n", 466 | " return False" 467 | ], 468 | "execution_count": 0, 469 | "outputs": [] 470 | }, 471 | { 472 | "cell_type": "code", 473 | "metadata": { 474 | "id": "AGGujN9M_-ZU", 475 | "colab_type": "code", 476 | "outputId": "8231f73c-1d58-4c76-d587-5ee1928e67a3", 477 | "colab": { 478 | "base_uri": "https://localhost:8080/", 479 | "height": 35 480 | } 481 | }, 482 | "source": [ 483 | "hasCycle(head_cycle), hasCycle(head1)" 484 | ], 485 | "execution_count": 0, 486 | "outputs": [ 487 | { 488 | "output_type": "execute_result", 489 | "data": { 490 | "text/plain": [ 491 | "(True, False)" 492 | ] 493 | }, 494 | "metadata": { 495 | "tags": [] 496 | }, 497 | "execution_count": 41 498 | } 499 | ] 500 | }, 501 | { 502 | "cell_type": "markdown", 503 | "metadata": { 504 | "id": "BJxOVKPVAUTK", 505 | "colab_type": "text" 506 | }, 507 | "source": [ 508 | "### [Check where the cycle starts](https://leetcode.com/problems/linked-list-cycle-ii/)" 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "metadata": { 514 | "id": "lMkK9SxGFtlU", 515 | "colab_type": "code", 516 | "colab": {} 517 | }, 518 | "source": [ 519 | "def detectCycle(head):\n", 520 | " slow = fast = head\n", 521 | "\n", 522 | " def getStartNode(slow, fast, head):\n", 523 | " # Reset slow pointer \n", 524 | " slow = head\n", 525 | " while fast and slow != fast:\n", 526 | " slow = slow.next\n", 527 | " fast = fast.next\n", 528 | " return slow\n", 529 | "\n", 530 | " while fast and fast.next:\n", 531 | " slow = slow.next\n", 532 | " fast = fast.next.next\n", 533 | " # A cycle is detected\n", 534 | " if slow == fast: \n", 535 | " return getStartNode(slow, fast, head)\n", 536 | " \n", 537 | " return None\n" 538 | ], 539 | "execution_count": 0, 540 | "outputs": [] 541 | }, 542 | { 543 | "cell_type": "code", 544 | "metadata": { 545 | "id": "ZlC_JS3zGoAs", 546 | "colab_type": "code", 547 | "outputId": "a4f45ccf-bf95-4408-83f5-a7e98ee75c4e", 548 | "colab": { 549 | "base_uri": "https://localhost:8080/", 550 | "height": 35 551 | } 552 | }, 553 | "source": [ 554 | "detectCycle(head_cycle).val, detectCycle(head1)" 555 | ], 556 | "execution_count": 0, 557 | "outputs": [ 558 | { 559 | "output_type": "execute_result", 560 | "data": { 561 | "text/plain": [ 562 | "(3, None)" 563 | ] 564 | }, 565 | "metadata": { 566 | "tags": [] 567 | }, 568 | "execution_count": 43 569 | } 570 | ] 571 | }, 572 | { 573 | "cell_type": "code", 574 | "metadata": { 575 | "id": "2Yu3lZROJRd0", 576 | "colab_type": "code", 577 | "colab": {} 578 | }, 579 | "source": [ 580 | "def resetLastNode(slow, fast, head):\n", 581 | " slow = head\n", 582 | " while fast and slow.next != fast.next:\n", 583 | " slow = slow.next\n", 584 | " fast = fast.next\n", 585 | " fast.next = None" 586 | ], 587 | "execution_count": 0, 588 | "outputs": [] 589 | }, 590 | { 591 | "cell_type": "code", 592 | "metadata": { 593 | "id": "klgtZzC8J1p5", 594 | "colab_type": "code", 595 | "colab": {} 596 | }, 597 | "source": [ 598 | "def removeCycle(head):\n", 599 | " slow = fast = head\n", 600 | "\n", 601 | " while fast and fast.next:\n", 602 | " slow = slow.next\n", 603 | " fast = fast.next.next\n", 604 | " # A cycle is detected\n", 605 | " if slow == fast: \n", 606 | " resetLastNode(slow, fast, head)\n", 607 | " return \n", 608 | " return " 609 | ], 610 | "execution_count": 0, 611 | "outputs": [] 612 | }, 613 | { 614 | "cell_type": "code", 615 | "metadata": { 616 | "id": "Hkfwf1ZHJ_ee", 617 | "colab_type": "code", 618 | "outputId": "c92543cb-be01-46ed-c8b5-c3cbb9f789d8", 619 | "colab": { 620 | "base_uri": "https://localhost:8080/", 621 | "height": 127 622 | } 623 | }, 624 | "source": [ 625 | "removeCycle(head_cycle)\n", 626 | "iterate(head_cycle)" 627 | ], 628 | "execution_count": 0, 629 | "outputs": [ 630 | { 631 | "output_type": "stream", 632 | "text": [ 633 | "1\n", 634 | "2\n", 635 | "3\n", 636 | "4\n", 637 | "5\n", 638 | "6\n" 639 | ], 640 | "name": "stdout" 641 | } 642 | ] 643 | }, 644 | { 645 | "cell_type": "markdown", 646 | "metadata": { 647 | "id": "XRirMOVAnF_P", 648 | "colab_type": "text" 649 | }, 650 | "source": [ 651 | "# Opposite-directional Pointers" 652 | ] 653 | }, 654 | { 655 | "cell_type": "code", 656 | "metadata": { 657 | "id": "sHZyeFkjoSLT", 658 | "colab_type": "code", 659 | "colab": {} 660 | }, 661 | "source": [ 662 | "# Reverse a list or string in place\n", 663 | "def reverse(a):\n", 664 | " i, j = 0, len(a) - 1\n", 665 | " while i < j:\n", 666 | " # Swap items\n", 667 | " a[i], a[j] = a[j], a[i]\n", 668 | " i += 1\n", 669 | " j -= 1" 670 | ], 671 | "execution_count": 0, 672 | "outputs": [] 673 | }, 674 | { 675 | "cell_type": "code", 676 | "metadata": { 677 | "id": "8Mcrgto4oFhP", 678 | "colab_type": "code", 679 | "colab": { 680 | "base_uri": "https://localhost:8080/", 681 | "height": 35 682 | }, 683 | "outputId": "4732a45f-bd29-4ccb-d6cc-2bd8be5ba731" 684 | }, 685 | "source": [ 686 | "# Reverse a list\n", 687 | "a = [1, 2, 3, 4, 5]\n", 688 | "b = 'abcd'\n", 689 | "b = list(b)\n", 690 | "reverse(a), reverse(b)\n", 691 | "a, b" 692 | ], 693 | "execution_count": 5, 694 | "outputs": [ 695 | { 696 | "output_type": "execute_result", 697 | "data": { 698 | "text/plain": [ 699 | "([5, 4, 3, 2, 1], ['d', 'c', 'b', 'a'])" 700 | ] 701 | }, 702 | "metadata": { 703 | "tags": [] 704 | }, 705 | "execution_count": 5 706 | } 707 | ] 708 | }, 709 | { 710 | "cell_type": "markdown", 711 | "metadata": { 712 | "id": "peRFBx9ToIMH", 713 | "colab_type": "text" 714 | }, 715 | "source": [ 716 | "## Two Sum" 717 | ] 718 | }, 719 | { 720 | "cell_type": "code", 721 | "metadata": { 722 | "id": "a-VwPo3nnaGU", 723 | "colab_type": "code", 724 | "colab": {} 725 | }, 726 | "source": [ 727 | "def twoSum(a, target):\n", 728 | " n = len(a)\n", 729 | " i, j = 0, n-1\n", 730 | " while i < j:\n", 731 | " temp = a[i] + a[j]\n", 732 | " if temp == target:\n", 733 | " return [i, j]\n", 734 | " elif temp < target:\n", 735 | " i += 1\n", 736 | " else:\n", 737 | " j -= 1\n", 738 | " return []" 739 | ], 740 | "execution_count": 0, 741 | "outputs": [] 742 | }, 743 | { 744 | "cell_type": "code", 745 | "metadata": { 746 | "id": "qE4rNc_yn0ru", 747 | "colab_type": "code", 748 | "colab": { 749 | "base_uri": "https://localhost:8080/", 750 | "height": 35 751 | }, 752 | "outputId": "0e3f7c1d-2f47-487c-f1bf-644255f4214e" 753 | }, 754 | "source": [ 755 | "a = [2, 5, 7, 11, 15]\n", 756 | "target = 9\n", 757 | "twoSum(a, target)" 758 | ], 759 | "execution_count": 2, 760 | "outputs": [ 761 | { 762 | "output_type": "execute_result", 763 | "data": { 764 | "text/plain": [ 765 | "[0, 2]" 766 | ] 767 | }, 768 | "metadata": { 769 | "tags": [] 770 | }, 771 | "execution_count": 2 772 | } 773 | ] 774 | }, 775 | { 776 | "cell_type": "markdown", 777 | "metadata": { 778 | "id": "X0Epx9cJWTPC", 779 | "colab_type": "text" 780 | }, 781 | "source": [ 782 | "# Three Pointers" 783 | ] 784 | }, 785 | { 786 | "cell_type": "code", 787 | "metadata": { 788 | "id": "M2XkxgxUWWMd", 789 | "colab_type": "code", 790 | "colab": {} 791 | }, 792 | "source": [ 793 | "a = [1, 0, 1, 0, 1]\n", 794 | "S = 2" 795 | ], 796 | "execution_count": 0, 797 | "outputs": [] 798 | }, 799 | { 800 | "cell_type": "code", 801 | "metadata": { 802 | "id": "-wD9AJE9Wa81", 803 | "colab_type": "code", 804 | "colab": {} 805 | }, 806 | "source": [ 807 | "# Try two pointers\n", 808 | "def numSubarraysWithSum(a, S):\n", 809 | " i, j = 0, 0\n", 810 | " win_sum = 0\n", 811 | " ans = 0\n", 812 | " while j < len(a):\n", 813 | " win_sum += a[j]\n", 814 | " while i S:\n", 815 | " win_sum -= a[i]\n", 816 | " i += 1\n", 817 | " if win_sum == S:\n", 818 | " ans += 1\n", 819 | " print('({}, {})'.format(i, j))\n", 820 | " j += 1\n", 821 | " return ans" 822 | ], 823 | "execution_count": 0, 824 | "outputs": [] 825 | }, 826 | { 827 | "cell_type": "code", 828 | "metadata": { 829 | "id": "NLKtEwQUXaQD", 830 | "colab_type": "code", 831 | "colab": { 832 | "base_uri": "https://localhost:8080/", 833 | "height": 90 834 | }, 835 | "outputId": "783f296b-4ad1-422e-c927-5e475e573874" 836 | }, 837 | "source": [ 838 | "numSubarraysWithSum(a, S)" 839 | ], 840 | "execution_count": 7, 841 | "outputs": [ 842 | { 843 | "output_type": "stream", 844 | "text": [ 845 | "(0, 2)\n", 846 | "(0, 3)\n", 847 | "(1, 4)\n" 848 | ], 849 | "name": "stdout" 850 | }, 851 | { 852 | "output_type": "execute_result", 853 | "data": { 854 | "text/plain": [ 855 | "3" 856 | ] 857 | }, 858 | "metadata": { 859 | "tags": [] 860 | }, 861 | "execution_count": 7 862 | } 863 | ] 864 | }, 865 | { 866 | "cell_type": "markdown", 867 | "metadata": { 868 | "id": "DdmOnfQNYP1O", 869 | "colab_type": "text" 870 | }, 871 | "source": [ 872 | "We can clearly see that it missed the case $(2, 4)$. Why? Because we are restricting the subarray sum in range $[i, j]$ to be smaller than or equal to $S$, with the occruence of $0$s that might appear in the front or in the rear of the subarray:\n", 873 | "* In the process of expanding the subarray, pointer $j$ is moved one at a time. Thus, even though $0$s appear in the rear of the subarray, the counting is correct.\n", 874 | "* However, in the process of shrinking the subarray while the restriction is violated($sum > S$), we stop right away once $sum \\leq S$. And in the code, we end up only counting it as one occurrence. With $0$s at the beginning of the subarray, such as the subarray $[0, 1, 0, 1]$ with index $1$ and $4$, there count should be two instead of one. " 875 | ] 876 | }, 877 | { 878 | "cell_type": "code", 879 | "metadata": { 880 | "id": "XTTf6yb8hy5f", 881 | "colab_type": "code", 882 | "colab": {} 883 | }, 884 | "source": [ 885 | "def numSubarraysWithSum(a, S):\n", 886 | " i, i_h, j = 0, 0, 0\n", 887 | " win_sum = 0\n", 888 | " ans = 0\n", 889 | " while j < len(a):\n", 890 | " win_sum += a[j]\n", 891 | " while i < j and win_sum > S:\n", 892 | " win_sum -= a[i]\n", 893 | " i += 1\n", 894 | " # Move i_h to count all zeros in the front\n", 895 | " i_h = i\n", 896 | " while i_h < j and win_sum == S and a[i_h] == 0:\n", 897 | " print('({}, {})'.format(i_h, j))\n", 898 | " ans += 1\n", 899 | " i_h += 1\n", 900 | "\n", 901 | " if win_sum == S:\n", 902 | " ans += 1\n", 903 | " print('({}, {})'.format(i_h, j))\n", 904 | " j += 1\n", 905 | " return ans" 906 | ], 907 | "execution_count": 0, 908 | "outputs": [] 909 | }, 910 | { 911 | "cell_type": "code", 912 | "metadata": { 913 | "id": "yPmDad-RjCpw", 914 | "colab_type": "code", 915 | "colab": { 916 | "base_uri": "https://localhost:8080/", 917 | "height": 109 918 | }, 919 | "outputId": "9fbe3bf8-8cc9-4dd8-8edc-2b254edce79d" 920 | }, 921 | "source": [ 922 | "numSubarraysWithSum(a, S)" 923 | ], 924 | "execution_count": 9, 925 | "outputs": [ 926 | { 927 | "output_type": "stream", 928 | "text": [ 929 | "(0, 2)\n", 930 | "(0, 3)\n", 931 | "(1, 4)\n", 932 | "(2, 4)\n" 933 | ], 934 | "name": "stdout" 935 | }, 936 | { 937 | "output_type": "execute_result", 938 | "data": { 939 | "text/plain": [ 940 | "4" 941 | ] 942 | }, 943 | "metadata": { 944 | "tags": [] 945 | }, 946 | "execution_count": 9 947 | } 948 | ] 949 | } 950 | ] 951 | } -------------------------------------------------------------------------------- /chapter_python_comparison_sorting.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "chapter_python_comparison_sorting.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [], 9 | "toc_visible": true, 10 | "include_colab_link": true 11 | }, 12 | "kernelspec": { 13 | "name": "python3", 14 | "display_name": "Python 3" 15 | } 16 | }, 17 | "cells": [ 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "id": "view-in-github", 22 | "colab_type": "text" 23 | }, 24 | "source": [ 25 | "\"Open" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": { 31 | "id": "fdKUnCibJGfe", 32 | "colab_type": "text" 33 | }, 34 | "source": [ 35 | "Python offers a variety of built-in functions, modules, and libraries to help with comparison, sorint, and selections." 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": { 41 | "id": "Js7-4f1M71PF", 42 | "colab_type": "text" 43 | }, 44 | "source": [ 45 | "## Comparison operators" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "metadata": { 51 | "id": "dtlOO7PU_-Wz", 52 | "colab_type": "code", 53 | "outputId": "9120041c-ebcd-4082-b61a-48425a1ec45c", 54 | "colab": { 55 | "base_uri": "https://localhost:8080/", 56 | "height": 35 57 | } 58 | }, 59 | "source": [ 60 | "# Compare numericals\n", 61 | "c1 = 2 < 3\n", 62 | "c2 = 2.5 > 3\n", 63 | "c1, c2" 64 | ], 65 | "execution_count": 0, 66 | "outputs": [ 67 | { 68 | "output_type": "execute_result", 69 | "data": { 70 | "text/plain": [ 71 | "(True, False)" 72 | ] 73 | }, 74 | "metadata": { 75 | "tags": [] 76 | }, 77 | "execution_count": 8 78 | } 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "metadata": { 84 | "id": "3SB8i6NE9eMM", 85 | "colab_type": "code", 86 | "outputId": "70380bfa-49fe-4611-d0f2-2f6e76ec5be9", 87 | "colab": { 88 | "base_uri": "https://localhost:8080/", 89 | "height": 35 90 | } 91 | }, 92 | "source": [ 93 | "# Compare strings\n", 94 | "c1 = 'ab' < 'bc'\n", 95 | "c2 = 'abc' > 'abd'\n", 96 | "c3 = 'ab' < 'abab'\n", 97 | "c4 = 'abc' != 'abc'\n", 98 | "c1, c2, c3, c4" 99 | ], 100 | "execution_count": 0, 101 | "outputs": [ 102 | { 103 | "output_type": "execute_result", 104 | "data": { 105 | "text/plain": [ 106 | "(True, False, True, False)" 107 | ] 108 | }, 109 | "metadata": { 110 | "tags": [] 111 | }, 112 | "execution_count": 10 113 | } 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "metadata": { 119 | "id": "5ePi3mnw9stn", 120 | "colab_type": "code", 121 | "outputId": "1c05d2d6-89b1-4e9d-f1f1-bf3eb3c838dc", 122 | "colab": { 123 | "base_uri": "https://localhost:8080/", 124 | "height": 35 125 | } 126 | }, 127 | "source": [ 128 | "# Compare Sequences\n", 129 | "c1 = [1, 2, 3] < [2, 3]\n", 130 | "c2 = (1, 2) > (1, 2, 3)\n", 131 | "c3 = [1, 2] == [1, 2]\n", 132 | "c1, c2, c3" 133 | ], 134 | "execution_count": 0, 135 | "outputs": [ 136 | { 137 | "output_type": "execute_result", 138 | "data": { 139 | "text/plain": [ 140 | "(True, False, True)" 141 | ] 142 | }, 143 | "metadata": { 144 | "tags": [] 145 | }, 146 | "execution_count": 18 147 | } 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "metadata": { 153 | "id": "AYbdgocGCqNt", 154 | "colab_type": "code", 155 | "outputId": "71702e44-48ee-4319-e378-91c898bd2309", 156 | "colab": { 157 | "base_uri": "https://localhost:8080/", 158 | "height": 172 159 | } 160 | }, 161 | "source": [ 162 | "[1, 2, 3] < (2, 3)" 163 | ], 164 | "execution_count": 0, 165 | "outputs": [ 166 | { 167 | "output_type": "error", 168 | "ename": "TypeError", 169 | "evalue": "ignored", 170 | "traceback": [ 171 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 172 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 173 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 174 | "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'list' and 'tuple'" 175 | ] 176 | } 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "metadata": { 182 | "id": "XlA1fZxxCr44", 183 | "colab_type": "code", 184 | "outputId": "ffab3de3-5c39-4152-c233-816b3500492c", 185 | "colab": { 186 | "base_uri": "https://localhost:8080/", 187 | "height": 172 188 | } 189 | }, 190 | "source": [ 191 | "{1: 'a', 2:'b'} < {1: 'a', 2:'b', 3:'c'}" 192 | ], 193 | "execution_count": 0, 194 | "outputs": [ 195 | { 196 | "output_type": "error", 197 | "ename": "TypeError", 198 | "evalue": "ignored", 199 | "traceback": [ 200 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 201 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", 202 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34m{\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'a'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m'b'\u001b[0m\u001b[0;34m}\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'a'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m'b'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m'c'\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", 203 | "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'dict' and 'dict'" 204 | ] 205 | } 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "metadata": { 211 | "id": "FHjrUBMvJTqS", 212 | "colab_type": "text" 213 | }, 214 | "source": [ 215 | "## max() and min() built-in functions\n", 216 | "\n", 217 | "max(iterable, *[, key, default])\n", 218 | "max(arg1, arg2, *args[, key])\n", 219 | " If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.\n", 220 | "\n", 221 | " There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.\n", 222 | "\n", 223 | " If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).\n", 224 | "\n", 225 | " New in version 3.4: The default keyword-only argument.\n", 226 | "\n", 227 | " Changed in version 3.8: The key can be None.\n", 228 | "\n", 229 | "What is really interesting is that when we pass two iterables such as two lists into the $max$ function, it compares them as they are strings with lexicographical order. This character makes it useful to problem solving sometimes. \n" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "metadata": { 235 | "id": "Ysb8M9hNL42Z", 236 | "colab_type": "code", 237 | "outputId": "574e135e-f2be-4dd6-d15d-ea5cb914062d", 238 | "colab": { 239 | "base_uri": "https://localhost:8080/", 240 | "height": 35 241 | } 242 | }, 243 | "source": [ 244 | "# One iterable\n", 245 | "lst1 = [4, 8, 9, 20, 3]\n", 246 | "max([4, 8, 9, 20, 3])" 247 | ], 248 | "execution_count": 0, 249 | "outputs": [ 250 | { 251 | "output_type": "execute_result", 252 | "data": { 253 | "text/plain": [ 254 | "20" 255 | ] 256 | }, 257 | "metadata": { 258 | "tags": [] 259 | }, 260 | "execution_count": 3 261 | } 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "metadata": { 267 | "id": "Zcr-WC5sMFjc", 268 | "colab_type": "code", 269 | "outputId": "72ba2a72-0d14-4411-9f81-a25c06ee3873", 270 | "colab": { 271 | "base_uri": "https://localhost:8080/", 272 | "height": 35 273 | } 274 | }, 275 | "source": [ 276 | "# Two arguments\n", 277 | "m1 = max(24, 15)\n", 278 | "m2 = max([4, 8, 9, 20, 3], [6, 2, 8])\n", 279 | "m3 = max('abc', 'ba')\n", 280 | "m1, m2, m3" 281 | ], 282 | "execution_count": 0, 283 | "outputs": [ 284 | { 285 | "output_type": "execute_result", 286 | "data": { 287 | "text/plain": [ 288 | "(24, [6, 2, 8], 'ba')" 289 | ] 290 | }, 291 | "metadata": { 292 | "tags": [] 293 | }, 294 | "execution_count": 5 295 | } 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "metadata": { 301 | "id": "ilxRqKv5MygZ", 302 | "colab_type": "code", 303 | "outputId": "6201a811-9e8e-4b24-d51f-f9d64eb9e32c", 304 | "colab": { 305 | "base_uri": "https://localhost:8080/", 306 | "height": 35 307 | } 308 | }, 309 | "source": [ 310 | "" 311 | ], 312 | "execution_count": 0, 313 | "outputs": [ 314 | { 315 | "output_type": "execute_result", 316 | "data": { 317 | "text/plain": [ 318 | "'ba'" 319 | ] 320 | }, 321 | "metadata": { 322 | "tags": [] 323 | }, 324 | "execution_count": 5 325 | } 326 | ] 327 | }, 328 | { 329 | "cell_type": "code", 330 | "metadata": { 331 | "id": "Td_fQvXGM7Ss", 332 | "colab_type": "code", 333 | "outputId": "439e70b9-46eb-4fe7-cbb6-c254dd6d6785", 334 | "colab": { 335 | "base_uri": "https://localhost:8080/", 336 | "height": 35 337 | } 338 | }, 339 | "source": [ 340 | "# For dictionary, it defaultly compares with keys, and it returns the key\n", 341 | "dict1 = {'a': 5, 'b': 8, 'c': 3}\n", 342 | "k1 = max(dict1)\n", 343 | "k2 = max(dict1, key=dict1.get)\n", 344 | "k3 = max(dict1, key =lambda x: dict1[x])\n", 345 | "k1, k2, k3" 346 | ], 347 | "execution_count": 0, 348 | "outputs": [ 349 | { 350 | "output_type": "execute_result", 351 | "data": { 352 | "text/plain": [ 353 | "('c', 'b', 'b')" 354 | ] 355 | }, 356 | "metadata": { 357 | "tags": [] 358 | }, 359 | "execution_count": 9 360 | } 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "metadata": { 366 | "id": "b2A71c2JTA3r", 367 | "colab_type": "code", 368 | "outputId": "898c9b40-bfd5-4625-b69f-d3e009e35ca1", 369 | "colab": { 370 | "base_uri": "https://localhost:8080/", 371 | "height": 35 372 | } 373 | }, 374 | "source": [ 375 | "max([], default=0)" 376 | ], 377 | "execution_count": 0, 378 | "outputs": [ 379 | { 380 | "output_type": "execute_result", 381 | "data": { 382 | "text/plain": [ 383 | "0" 384 | ] 385 | }, 386 | "metadata": { 387 | "tags": [] 388 | }, 389 | "execution_count": 2 390 | } 391 | ] 392 | }, 393 | { 394 | "cell_type": "markdown", 395 | "metadata": { 396 | "id": "0yLoqm8ZyaWM", 397 | "colab_type": "text" 398 | }, 399 | "source": [ 400 | "## Rich Comparison" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "metadata": { 406 | "id": "BJDcW18ry4HS", 407 | "colab_type": "code", 408 | "colab": {} 409 | }, 410 | "source": [ 411 | "from functools import total_ordering\n", 412 | "\n", 413 | "@total_ordering\n", 414 | "class Person(object):\n", 415 | " def __init__(self, firstname, lastname):\n", 416 | " self.first = firstname\n", 417 | " self.last = lastname\n", 418 | "\n", 419 | " def __eq__(self, other):\n", 420 | " return ((self.last, self.first) == (other.last, other.first))\n", 421 | " \n", 422 | " def __ne__(self, other):\n", 423 | " return not (self == other)\n", 424 | "\n", 425 | " def __lt__(self, other):\n", 426 | " return ((self.last, self.first) < (other.last, other.first))\n", 427 | "\n", 428 | " def __repr__(self):\n", 429 | " return \"%s %s\" % (self.first, self.last)" 430 | ], 431 | "execution_count": 0, 432 | "outputs": [] 433 | }, 434 | { 435 | "cell_type": "code", 436 | "metadata": { 437 | "id": "zeww0AgS3p6R", 438 | "colab_type": "code", 439 | "colab": { 440 | "base_uri": "https://localhost:8080/", 441 | "height": 35 442 | }, 443 | "outputId": "c8eec9ba-6623-48cd-a1bc-5e44eafb36f5" 444 | }, 445 | "source": [ 446 | "p1 = Person('Li', 'Yin')\n", 447 | "p2 = Person('Bella', 'Smith')\n", 448 | "p1 > p2" 449 | ], 450 | "execution_count": 36, 451 | "outputs": [ 452 | { 453 | "output_type": "execute_result", 454 | "data": { 455 | "text/plain": [ 456 | "True" 457 | ] 458 | }, 459 | "metadata": { 460 | "tags": [] 461 | }, 462 | "execution_count": 36 463 | } 464 | ] 465 | }, 466 | { 467 | "cell_type": "markdown", 468 | "metadata": { 469 | "id": "j9da_uDkJYQr", 470 | "colab_type": "text" 471 | }, 472 | "source": [ 473 | "## seq.sort() and sorted()" 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": { 479 | "id": "ag6v7yjLmR80", 480 | "colab_type": "text" 481 | }, 482 | "source": [ 483 | "### Basics" 484 | ] 485 | }, 486 | { 487 | "cell_type": "code", 488 | "metadata": { 489 | "id": "fJdwJaQkgc9l", 490 | "colab_type": "code", 491 | "outputId": "ab889de3-3fe1-4a0c-a54e-5b8a231f26e4", 492 | "colab": { 493 | "base_uri": "https://localhost:8080/", 494 | "height": 35 495 | } 496 | }, 497 | "source": [ 498 | "# List bulti-in in-place sort\n", 499 | "lst = [4, 5, 8, 1, 2, 7]\n", 500 | "lst.sort()\n", 501 | "lst" 502 | ], 503 | "execution_count": 0, 504 | "outputs": [ 505 | { 506 | "output_type": "execute_result", 507 | "data": { 508 | "text/plain": [ 509 | "[1, 2, 4, 5, 7, 8]" 510 | ] 511 | }, 512 | "metadata": { 513 | "tags": [] 514 | }, 515 | "execution_count": 7 516 | } 517 | ] 518 | }, 519 | { 520 | "cell_type": "code", 521 | "metadata": { 522 | "id": "LvOw_sH9hHG2", 523 | "colab_type": "code", 524 | "outputId": "b143c999-8934-42c1-eec3-384c4715fd1a", 525 | "colab": { 526 | "base_uri": "https://localhost:8080/", 527 | "height": 35 528 | } 529 | }, 530 | "source": [ 531 | "# sorted() out-of-place sorting\n", 532 | "lst = [4, 5, 8, 1, 2, 7]\n", 533 | "new_lst = sorted(lst)\n", 534 | "new_lst, lst" 535 | ], 536 | "execution_count": 0, 537 | "outputs": [ 538 | { 539 | "output_type": "execute_result", 540 | "data": { 541 | "text/plain": [ 542 | "([1, 2, 4, 5, 7, 8], [4, 5, 8, 1, 2, 7])" 543 | ] 544 | }, 545 | "metadata": { 546 | "tags": [] 547 | }, 548 | "execution_count": 9 549 | } 550 | ] 551 | }, 552 | { 553 | "cell_type": "code", 554 | "metadata": { 555 | "id": "B0qx9rvaser4", 556 | "colab_type": "code", 557 | "outputId": "2326e9a9-a761-4d0b-9147-8379baa53e64", 558 | "colab": { 559 | "base_uri": "https://localhost:8080/", 560 | "height": 209 561 | } 562 | }, 563 | "source": [ 564 | "# cant sort other iterable with .sort()\n", 565 | "tup = (3, 6, 8, 2, 78, 1, 23, 45, 9)\n", 566 | "tup.sort()" 567 | ], 568 | "execution_count": 0, 569 | "outputs": [ 570 | { 571 | "output_type": "error", 572 | "ename": "AttributeError", 573 | "evalue": "ignored", 574 | "traceback": [ 575 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 576 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 577 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m6\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m8\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m78\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m23\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m45\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m9\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mtup\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;31m#sorted(tup)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", 578 | "\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'sort'" 579 | ] 580 | } 581 | ] 582 | }, 583 | { 584 | "cell_type": "code", 585 | "metadata": { 586 | "id": "aM1KExWNk33x", 587 | "colab_type": "code", 588 | "outputId": "ef49fd48-4c27-4854-e437-9d9c262dea24", 589 | "colab": { 590 | "base_uri": "https://localhost:8080/", 591 | "height": 35 592 | } 593 | }, 594 | "source": [ 595 | "# Sort iterable with sorted()\n", 596 | "fruit = ('apple', 'pear', 'berry', 'peach', 'apricot')\n", 597 | "new_fruit = sorted(fruit)\n", 598 | "new_fruit" 599 | ], 600 | "execution_count": 0, 601 | "outputs": [ 602 | { 603 | "output_type": "execute_result", 604 | "data": { 605 | "text/plain": [ 606 | "['apple', 'apricot', 'berry', 'peach', 'pear']" 607 | ] 608 | }, 609 | "metadata": { 610 | "tags": [] 611 | }, 612 | "execution_count": 11 613 | } 614 | ] 615 | }, 616 | { 617 | "cell_type": "code", 618 | "metadata": { 619 | "id": "ugBtubRqksNR", 620 | "colab_type": "code", 621 | "colab": {} 622 | }, 623 | "source": [ 624 | "tup = (3, 6, 8, 2, 78, 1, 23, 45, 9)" 625 | ], 626 | "execution_count": 0, 627 | "outputs": [] 628 | }, 629 | { 630 | "cell_type": "code", 631 | "metadata": { 632 | "id": "rVASApvegGrB", 633 | "colab_type": "code", 634 | "outputId": "87b4a560-a789-4c33-a500-d8b236dcea18", 635 | "colab": { 636 | "base_uri": "https://localhost:8080/", 637 | "height": 35 638 | } 639 | }, 640 | "source": [ 641 | "lst = list(tup)\n", 642 | "lst.sort()\n", 643 | "lst\n" 644 | ], 645 | "execution_count": 0, 646 | "outputs": [ 647 | { 648 | "output_type": "execute_result", 649 | "data": { 650 | "text/plain": [ 651 | "[1, 2, 3, 6, 8, 9, 23, 45, 78]" 652 | ] 653 | }, 654 | "metadata": { 655 | "tags": [] 656 | }, 657 | "execution_count": 5 658 | } 659 | ] 660 | }, 661 | { 662 | "cell_type": "code", 663 | "metadata": { 664 | "id": "0DJi8M9N535w", 665 | "colab_type": "code", 666 | "colab": {} 667 | }, 668 | "source": [ 669 | "## Customize key\n", 670 | "def cmp(x, y):\n", 671 | " return y - x" 672 | ], 673 | "execution_count": 0, 674 | "outputs": [] 675 | }, 676 | { 677 | "cell_type": "code", 678 | "metadata": { 679 | "id": "I_X20Gc-58RE", 680 | "colab_type": "code", 681 | "colab": { 682 | "base_uri": "https://localhost:8080/", 683 | "height": 35 684 | }, 685 | "outputId": "af0499e1-3661-4092-f54b-ebd1c660a4e1" 686 | }, 687 | "source": [ 688 | "from functools import cmp_to_key\n", 689 | "lst = [4, 5, 8, 1, 2, 7]\n", 690 | "lst.sort(key=cmp_to_key(cmp))\n", 691 | "lst" 692 | ], 693 | "execution_count": 59, 694 | "outputs": [ 695 | { 696 | "output_type": "execute_result", 697 | "data": { 698 | "text/plain": [ 699 | "[8, 7, 5, 4, 2, 1]" 700 | ] 701 | }, 702 | "metadata": { 703 | "tags": [] 704 | }, 705 | "execution_count": 59 706 | } 707 | ] 708 | }, 709 | { 710 | "cell_type": "markdown", 711 | "metadata": { 712 | "id": "rCWeiCAGnNFP", 713 | "colab_type": "text" 714 | }, 715 | "source": [ 716 | "### Arguments" 717 | ] 718 | }, 719 | { 720 | "cell_type": "code", 721 | "metadata": { 722 | "id": "Y5YH4QJRnOtM", 723 | "colab_type": "code", 724 | "outputId": "b85028bc-9010-4a44-f05f-b2584a4f7c7b", 725 | "colab": { 726 | "base_uri": "https://localhost:8080/", 727 | "height": 35 728 | } 729 | }, 730 | "source": [ 731 | "# Reverse\n", 732 | "lst = [4, 5, 8, 1, 2, 7]\n", 733 | "lst.sort(reverse=True)\n", 734 | "lst" 735 | ], 736 | "execution_count": 0, 737 | "outputs": [ 738 | { 739 | "output_type": "execute_result", 740 | "data": { 741 | "text/plain": [ 742 | "[8, 7, 5, 4, 2, 1]" 743 | ] 744 | }, 745 | "metadata": { 746 | "tags": [] 747 | }, 748 | "execution_count": 12 749 | } 750 | ] 751 | }, 752 | { 753 | "cell_type": "code", 754 | "metadata": { 755 | "id": "y_dOIXFqotZA", 756 | "colab_type": "code", 757 | "colab": {} 758 | }, 759 | "source": [ 760 | "class Int(int):\n", 761 | " def __init__(self, val):\n", 762 | " self.val = val\n", 763 | " def __lt__(self, other):\n", 764 | " return other.val < self.val" 765 | ], 766 | "execution_count": 0, 767 | "outputs": [] 768 | }, 769 | { 770 | "cell_type": "code", 771 | "metadata": { 772 | "id": "8qdEy_ctpZcI", 773 | "colab_type": "code", 774 | "outputId": "542e0581-00e4-4306-cf72-f43f2c47716f", 775 | "colab": { 776 | "base_uri": "https://localhost:8080/", 777 | "height": 35 778 | } 779 | }, 780 | "source": [ 781 | "lst = [Int(4), Int(5), Int(8), Int(1), Int(2), Int(7)]\n", 782 | "lst.sort()\n", 783 | "lst" 784 | ], 785 | "execution_count": 38, 786 | "outputs": [ 787 | { 788 | "output_type": "execute_result", 789 | "data": { 790 | "text/plain": [ 791 | "[8, 7, 5, 4, 2, 1]" 792 | ] 793 | }, 794 | "metadata": { 795 | "tags": [] 796 | }, 797 | "execution_count": 38 798 | } 799 | ] 800 | }, 801 | { 802 | "cell_type": "code", 803 | "metadata": { 804 | "id": "HJ-elndv7iDD", 805 | "colab_type": "code", 806 | "colab": {} 807 | }, 808 | "source": [ 809 | "lst = [(8, 1), (5, 7), (4, 1), (1, 3), (2, 4)]" 810 | ], 811 | "execution_count": 0, 812 | "outputs": [] 813 | }, 814 | { 815 | "cell_type": "code", 816 | "metadata": { 817 | "id": "v1jkMSha7CeW", 818 | "colab_type": "code", 819 | "colab": { 820 | "base_uri": "https://localhost:8080/", 821 | "height": 35 822 | }, 823 | "outputId": "97317155-9f42-4a78-b6a7-cd8994232721" 824 | }, 825 | "source": [ 826 | "## Trhough a function\n", 827 | "def get_key(x):\n", 828 | " return x[1]\n", 829 | "new_lst = sorted(lst, key = get_key)\n", 830 | "new_lst" 831 | ], 832 | "execution_count": 52, 833 | "outputs": [ 834 | { 835 | "output_type": "execute_result", 836 | "data": { 837 | "text/plain": [ 838 | "[(8, 1), (4, 1), (1, 3), (2, 4), (5, 7)]" 839 | ] 840 | }, 841 | "metadata": { 842 | "tags": [] 843 | }, 844 | "execution_count": 52 845 | } 846 | ] 847 | }, 848 | { 849 | "cell_type": "code", 850 | "metadata": { 851 | "id": "5h4XOS_y7sKM", 852 | "colab_type": "code", 853 | "colab": { 854 | "base_uri": "https://localhost:8080/", 855 | "height": 35 856 | }, 857 | "outputId": "429a0632-f00e-422b-de9f-a846a8718c7d" 858 | }, 859 | "source": [ 860 | "# Through lambda function\n", 861 | "new_lst = sorted(lst, key = lambda x: x[1])\n", 862 | "new_lst" 863 | ], 864 | "execution_count": 53, 865 | "outputs": [ 866 | { 867 | "output_type": "execute_result", 868 | "data": { 869 | "text/plain": [ 870 | "[(8, 1), (4, 1), (1, 3), (2, 4), (5, 7)]" 871 | ] 872 | }, 873 | "metadata": { 874 | "tags": [] 875 | }, 876 | "execution_count": 53 877 | } 878 | ] 879 | }, 880 | { 881 | "cell_type": "code", 882 | "metadata": { 883 | "id": "iVMU4_4a7zjh", 884 | "colab_type": "code", 885 | "colab": { 886 | "base_uri": "https://localhost:8080/", 887 | "height": 35 888 | }, 889 | "outputId": "3ac52a3b-e17e-438b-de1a-119ff040d7d2" 890 | }, 891 | "source": [ 892 | "new_lst = sorted(lst, key = lambda x: (x[1], x[0]))\n", 893 | "new_lst" 894 | ], 895 | "execution_count": 54, 896 | "outputs": [ 897 | { 898 | "output_type": "execute_result", 899 | "data": { 900 | "text/plain": [ 901 | "[(4, 1), (8, 1), (1, 3), (2, 4), (5, 7)]" 902 | ] 903 | }, 904 | "metadata": { 905 | "tags": [] 906 | }, 907 | "execution_count": 54 908 | } 909 | ] 910 | }, 911 | { 912 | "cell_type": "code", 913 | "metadata": { 914 | "id": "eS-KOH4Y_3WO", 915 | "colab_type": "code", 916 | "colab": {} 917 | }, 918 | "source": [ 919 | "# A class\n", 920 | "class Student(object):\n", 921 | " def __init__(self, name, grade, age):\n", 922 | " self.name = name\n", 923 | " self.grade = grade\n", 924 | " self.age = age\n", 925 | " \n", 926 | " # To support indexing\n", 927 | " def __getitem__(self, key):\n", 928 | " return (self.name, self.grade, self.age)[key]\n", 929 | "\n", 930 | " def __repr__(self):\n", 931 | " return repr((self.name, self.grade, self.age))" 932 | ], 933 | "execution_count": 0, 934 | "outputs": [] 935 | }, 936 | { 937 | "cell_type": "code", 938 | "metadata": { 939 | "id": "cFYLwtZn_-qL", 940 | "colab_type": "code", 941 | "colab": { 942 | "base_uri": "https://localhost:8080/", 943 | "height": 35 944 | }, 945 | "outputId": "36f4f32b-2ee0-47de-e2bb-91e47d8bca08" 946 | }, 947 | "source": [ 948 | "students = [Student('john', 'A', 15), Student('jane', 'B', 12), Student('dave', 'B', 10)]\n", 949 | "sorted(students, key=lambda x: x.age)" 950 | ], 951 | "execution_count": 75, 952 | "outputs": [ 953 | { 954 | "output_type": "execute_result", 955 | "data": { 956 | "text/plain": [ 957 | "[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" 958 | ] 959 | }, 960 | "metadata": { 961 | "tags": [] 962 | }, 963 | "execution_count": 75 964 | } 965 | ] 966 | }, 967 | { 968 | "cell_type": "code", 969 | "metadata": { 970 | "id": "lshxkSOJBLiT", 971 | "colab_type": "code", 972 | "colab": { 973 | "base_uri": "https://localhost:8080/", 974 | "height": 35 975 | }, 976 | "outputId": "b2804f89-de0a-4cc7-c6af-6a7d26676625" 977 | }, 978 | "source": [ 979 | "# Use operator\n", 980 | "from operator import attrgetter\n", 981 | "sorted(students, key=attrgetter('age'))" 982 | ], 983 | "execution_count": 77, 984 | "outputs": [ 985 | { 986 | "output_type": "execute_result", 987 | "data": { 988 | "text/plain": [ 989 | "[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" 990 | ] 991 | }, 992 | "metadata": { 993 | "tags": [] 994 | }, 995 | "execution_count": 77 996 | } 997 | ] 998 | }, 999 | { 1000 | "cell_type": "code", 1001 | "metadata": { 1002 | "id": "nA1JzPi-CkIB", 1003 | "colab_type": "code", 1004 | "colab": { 1005 | "base_uri": "https://localhost:8080/", 1006 | "height": 35 1007 | }, 1008 | "outputId": "d2fc29e7-7217-41c8-ca77-b974f02feb3e" 1009 | }, 1010 | "source": [ 1011 | "from operator import attrgetter\n", 1012 | "sorted(students, key=attrgetter('grade', 'age'))" 1013 | ], 1014 | "execution_count": 78, 1015 | "outputs": [ 1016 | { 1017 | "output_type": "execute_result", 1018 | "data": { 1019 | "text/plain": [ 1020 | "[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]" 1021 | ] 1022 | }, 1023 | "metadata": { 1024 | "tags": [] 1025 | }, 1026 | "execution_count": 78 1027 | } 1028 | ] 1029 | }, 1030 | { 1031 | "cell_type": "code", 1032 | "metadata": { 1033 | "id": "mNhR68JvCZJ_", 1034 | "colab_type": "code", 1035 | "colab": { 1036 | "base_uri": "https://localhost:8080/", 1037 | "height": 35 1038 | }, 1039 | "outputId": "bb0937af-e97e-4c5e-f3da-4834129b283e" 1040 | }, 1041 | "source": [ 1042 | "# Use itemgetter\n", 1043 | "from operator import itemgetter\n", 1044 | "sorted(students, key=itemgetter(2))" 1045 | ], 1046 | "execution_count": 79, 1047 | "outputs": [ 1048 | { 1049 | "output_type": "execute_result", 1050 | "data": { 1051 | "text/plain": [ 1052 | "[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]" 1053 | ] 1054 | }, 1055 | "metadata": { 1056 | "tags": [] 1057 | }, 1058 | "execution_count": 79 1059 | } 1060 | ] 1061 | }, 1062 | { 1063 | "cell_type": "code", 1064 | "metadata": { 1065 | "id": "eA8dMPkksqly", 1066 | "colab_type": "code", 1067 | "outputId": "613cc186-cd57-4439-9f7f-6b122cd3d85b", 1068 | "colab": { 1069 | "base_uri": "https://localhost:8080/", 1070 | "height": 71 1071 | } 1072 | }, 1073 | "source": [ 1074 | "from collections import defaultdict\n", 1075 | "import random\n", 1076 | "dic = defaultdict(lambda: defaultdict(list)) # a dictionary of a dictionary of list dic[a][b] = [3, 1, 2, 4]\n", 1077 | "for i in range(10):\n", 1078 | " a = random.randint(1, 101)\n", 1079 | " b = random.randint(1, 101)\n", 1080 | " dic[a][b] = [random.randint(1, 101) for _ in range(10)]\n", 1081 | "print(dic) \n", 1082 | "sorted_dic = sorted(dic)\n", 1083 | "print(sorted_dic)" 1084 | ], 1085 | "execution_count": 0, 1086 | "outputs": [ 1087 | { 1088 | "output_type": "stream", 1089 | "text": [ 1090 | "defaultdict( at 0x7faf20e3c730>, {72: defaultdict(, {59: [63, 15, 62, 83, 30, 98, 16, 44, 58, 93]}), 82: defaultdict(, {70: [89, 49, 47, 63, 90, 1, 7, 9, 78, 10]}), 53: defaultdict(, {62: [10, 99, 35, 78, 74, 44, 82, 32, 32, 52]}), 78: defaultdict(, {78: [20, 22, 100, 29, 16, 65, 56, 8, 100, 100]}), 13: defaultdict(, {44: [4, 81, 17, 92, 44, 49, 72, 24, 13, 64]}), 84: defaultdict(, {47: [76, 94, 36, 56, 60, 87, 72, 47, 75, 33]}), 49: defaultdict(, {97: [7, 47, 13, 80, 85, 59, 2, 48, 68, 65]}), 87: defaultdict(, {61: [31, 72, 71, 63, 19, 84, 78, 80, 97, 85]}), 17: defaultdict(, {92: [29, 53, 20, 14, 16, 84, 57, 40, 4, 19]}), 54: defaultdict(, {32: [2, 31, 19, 31, 68, 10, 85, 34, 25, 62]})})\n", 1091 | "[13, 17, 49, 53, 54, 72, 78, 82, 84, 87]\n" 1092 | ], 1093 | "name": "stdout" 1094 | } 1095 | ] 1096 | }, 1097 | { 1098 | "cell_type": "code", 1099 | "metadata": { 1100 | "id": "VbmDX6yAvYax", 1101 | "colab_type": "code", 1102 | "outputId": "441aa86e-17c6-4cbd-b923-67c1ea41e384", 1103 | "colab": { 1104 | "base_uri": "https://localhost:8080/", 1105 | "height": 34 1106 | } 1107 | }, 1108 | "source": [ 1109 | "'''sort_list_of_tuple()'''\n", 1110 | "\n", 1111 | "lst = [(1, 8, 2), (3, 2, 9), (1, 7, 10), (1, 7, 1), (11, 1, 5), (6, 3, 10), (32, 18, 9)]\n", 1112 | "sorted_lst = sorted(lst, key = lambda x: x[0]) # sort in the order of the first element, and descresing order of the second element, and incresing of the third element\n", 1113 | "print(sorted_lst)" 1114 | ], 1115 | "execution_count": 0, 1116 | "outputs": [ 1117 | { 1118 | "output_type": "stream", 1119 | "text": [ 1120 | "[(1, 8, 2), (1, 7, 10), (1, 7, 1), (3, 2, 9), (6, 3, 10), (11, 1, 5), (32, 18, 9)]\n" 1121 | ], 1122 | "name": "stdout" 1123 | } 1124 | ] 1125 | }, 1126 | { 1127 | "cell_type": "code", 1128 | "metadata": { 1129 | "id": "tXDvRwd_047E", 1130 | "colab_type": "code", 1131 | "outputId": "231e3bd1-06df-4e6c-e4e8-ccfc7803ee62", 1132 | "colab": { 1133 | "base_uri": "https://localhost:8080/", 1134 | "height": 34 1135 | } 1136 | }, 1137 | "source": [ 1138 | "lst = [(1, 8, 2), (3, 2, 9), (1, 7, 10), (1, 7, 1), (11, 1, 5), (6, 3, 10), (32, 18, 9)]\n", 1139 | "sorted_lst = sorted(lst, key = lambda x: (x[0], -x[1], x[2])) # sort in the order of the first element, and descresing order of the second element, and incresing of the third element\n", 1140 | "print(sorted_lst)" 1141 | ], 1142 | "execution_count": 0, 1143 | "outputs": [ 1144 | { 1145 | "output_type": "stream", 1146 | "text": [ 1147 | "[(1, 8, 2), (1, 7, 1), (1, 7, 10), (3, 2, 9), (6, 3, 10), (11, 1, 5), (32, 18, 9)]\n" 1148 | ], 1149 | "name": "stdout" 1150 | } 1151 | ] 1152 | } 1153 | ] 1154 | } --------------------------------------------------------------------------------