Repository: keon/algorithms
Pull request #250 (2018-04-22 18:37:25)

naming conventions fixes
- resolved the conflicts from #242 in `test_maths.py`


Patch:
diff --git a/backtrack/array_sum_combinations.py b/backtrack/array_sum_combinations.py
index 6dbc103..b8dbc80 100644
--- a/backtrack/array_sum_combinations.py
+++ b/backtrack/array_sum_combinations.py
@@ -76,8 +76,8 @@ C = [1, 2, 2, 2]
 S = 7
 
 
-def check_sum(N, *nums):
-    if sum(x for x in nums) == N:
+def check_sum(n, *nums):
+    if sum(x for x in nums) == n:
         return (True, nums)
     else:
         return (False, nums)
diff --git a/calculator/math_parser.py b/calculator/math_parser.py
index 0437c8c..830d717 100644
--- a/calculator/math_parser.py
+++ b/calculator/math_parser.py
@@ -133,13 +133,13 @@ def main():
         simple user-interface
     """
     print("\t\tCalculator\n\n")
-    userInput = input("expression or exit: ")
-    while userInput != "exit":
+    user_input = input("expression or exit: ")
+    while user_input != "exit":
         try:
-            print("The result is {0}".format(evaluate(userInput)))
+            print("The result is {0}".format(evaluate(user_input)))
         except Exception:
             print("invalid syntax!")
-        userInput = input("expression or exit: ")
+            user_input = input("expression or exit: ")
     print("program end")
         
 
diff --git a/dfs/count_islands.py b/dfs/count_islands.py
index 5c47115..60f6802 100644
--- a/dfs/count_islands.py
+++ b/dfs/count_islands.py
@@ -27,18 +27,18 @@ def num_islands(grid):
     for i, row in enumerate(grid):
         for j, col in enumerate(grid[i]):
             if col == '1':
-                DFS(grid, i, j)
+                dfs(grid, i, j)
                 count += 1
     return count
 
 
-def DFS(grid, i, j):
+def dfs(grid, i, j):
     if (i < 0 or i >= len(grid)) or (j < 0 or len(grid[0])):
         return
     if grid[i][j] != '1':
         return
     grid[i][j] = '0'
-    DFS(grid, i+1, j)
-    DFS(grid, i-1, j)
-    DFS(grid, i, j+1)
-    DFS(grid, i, j-1)
+    dfs(grid, i+1, j)
+    dfs(grid, i-1, j)
+    dfs(grid, i, j+1)
+    dfs(grid, i, j-1)
diff --git a/dfs/pacific_atlantic.py b/dfs/pacific_atlantic.py
index 38f2c5c..984aa26 100644
--- a/dfs/pacific_atlantic.py
+++ b/dfs/pacific_atlantic.py
@@ -42,24 +42,24 @@ def pacific_atlantic(matrix):
     atlantic = [[False for _ in range (n)] for _ in range(m)]
     pacific =  [[False for _ in range (n)] for _ in range(m)]
     for i in range(n):
-        DFS(pacific, matrix, float("-inf"), i, 0)
-        DFS(atlantic, matrix, float("-inf"), i, m-1)
+        dfs(pacific, matrix, float("-inf"), i, 0)
+        dfs(atlantic, matrix, float("-inf"), i, m-1)
     for i in range(m):
-        DFS(pacific, matrix, float("-inf"), 0, i)
-        DFS(atlantic, matrix, float("-inf"), n-1, i)
+        dfs(pacific, matrix, float("-inf"), 0, i)
+        dfs(atlantic, matrix, float("-inf"), n-1, i)
     for i in range(n):
         for j in range(m):
             if pacific[i][j] and atlantic[i][j]:
                 res.append([i, j])
     return res
 
-def DFS(grid, matrix, height, i, j):
+def dfs(grid, matrix, height, i, j):
     if i < 0 or i >= len(matrix) or j < 0 or  j >= len(matrix[0]):
         return
     if grid[i][j] or matrix[i][j] < height:
         return
     grid[i][j] = True
-    DFS(grid, matrix, matrix[i][j], i-1, j)
-    DFS(grid, matrix, matrix[i][j], i+1, j)
-    DFS(grid, matrix, matrix[i][j], i, j-1)
-    DFS(grid, matrix, matrix[i][j], i, j+1)
+    dfs(grid, matrix, matrix[i][j], i-1, j)
+    dfs(grid, matrix, matrix[i][j], i+1, j)
+    dfs(grid, matrix, matrix[i][j], i, j-1)
+    dfs(grid, matrix, matrix[i][j], i, j+1)
diff --git a/dfs/walls_and_gates.py b/dfs/walls_and_gates.py
index 252cb7a..7d10b4d 100644
--- a/dfs/walls_and_gates.py
+++ b/dfs/walls_and_gates.py
@@ -7,16 +7,16 @@ def walls_and_gates(rooms):
     for i in range(len(rooms)):
         for j in range(len(rooms[0])):
             if rooms[i][j] == 0:
-                DFS(rooms, i, j, 0)
+                dfs(rooms, i, j, 0)
 
 
-def DFS(rooms, i, j, depth):
+def dfs(rooms, i, j, depth):
     if (i < 0 or i >= len(rooms)) or (j < 0 or j >= len(rooms[0])):
         return  # out of bounds
     if rooms[i][j] < depth:
         return  # crossed
     rooms[i][j] = depth
-    DFS(rooms, i+1, j, depth+1)
-    DFS(rooms, i-1, j, depth+1)
-    DFS(rooms, i, j+1, depth+1)
-    DFS(rooms, i, j-1, depth+1)
+    dfs(rooms, i+1, j, depth+1)
+    dfs(rooms, i-1, j, depth+1)
+    dfs(rooms, i, j+1, depth+1)
+    dfs(rooms, i, j-1, depth+1)
diff --git a/dp/coin_change.py b/dp/coin_change.py
index 6410f5b..dce9bb5 100644
--- a/dp/coin_change.py
+++ b/dp/coin_change.py
@@ -12,10 +12,10 @@ For N = 10 and S = [2, 5, 3, 6], there are five solutions:
 So the output should be 5.
 """
 
-def count(S, n):
+def count(s, n):
     # We need n+1 rows as the table is consturcted in bottom up
     # manner using the base case 0 value case (n = 0)
-    m = len(S)
+    m = len(s)
     table = [[0 for x in range(m)] for x in range(n+1)]
  
     # Fill the enteries for 0 value case (n = 0)
@@ -26,7 +26,7 @@ def count(S, n):
     for i in range(1, n+1):
         for j in range(m):
             # Count of solutions including S[j]
-            x = table[i - S[j]][j] if i-S[j] >= 0 else 0
+            x = table[i - s[j]][j] if i-s[j] >= 0 else 0
  
             # Count of solutions excluding S[j]
             y = table[i][j-1] if j >= 1 else 0
diff --git a/dp/egg_drop.py b/dp/egg_drop.py
index 3f71c3e..c087982 100644
--- a/dp/egg_drop.py
+++ b/dp/egg_drop.py
@@ -3,29 +3,29 @@ INT_MAX = 32767
  
 # Function to get minimum number of trials needed in worst
 # case with n eggs and k floors
-def eggDrop(n, k):
+def egg_drop(n, k):
     # A 2D table where entery eggFloor[i][j] will represent minimum
     # number of trials needed for i eggs and j floors.
-    eggFloor = [[0 for x in range(k+1)] for x in range(n+1)]
+    egg_floor = [[0 for x in range(k+1)] for x in range(n+1)]
  
     # We need one trial for one floor and0 trials for 0 floors
     for i in range(1, n+1):
-        eggFloor[i][1] = 1
-        eggFloor[i][0] = 0
+        egg_floor[i][1] = 1
+        egg_floor[i][0] = 0
  
     # We always need j trials for one egg and j floors.
     for j in range(1, k+1):
-        eggFloor[1][j] = j
+        egg_floor[1][j] = j
  
     # Fill rest of the entries in table using optimal substructure
     # property
     for i in range(2, n+1):
         for j in range(2, k+1):
-            eggFloor[i][j] = INT_MAX
+            egg_floor[i][j] = INT_MAX
             for x in range(1, j+1):
-                res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x])
-                if res < eggFloor[i][j]:
-                    eggFloor[i][j] = res
+                res = 1 + max(egg_floor[i-1][x-1], egg_floor[i][j-x])
+                if res < egg_floor[i][j]:
+                    egg_floor[i][j] = res
  
     # eggFloor[n][k] holds the result
-    return eggFloor[n][k]
+    return egg_floor[n][k]
diff --git a/dp/job_scheduling.py b/dp/job_scheduling.py
index b644303..7c72368 100644
--- a/dp/job_scheduling.py
+++ b/dp/job_scheduling.py
@@ -15,7 +15,7 @@ class Job:
 # returns -1 if all jobs before index conflict with it.
 # The array jobs[] is sorted in increasing order of finish
 # time.
-def binarySearch(job, start_index):
+def binary_search(job, start_index):
  
     # Initialize 'lo' and 'hi' for Binary Search
     lo = 0
@@ -51,12 +51,12 @@ def schedule(job):
     for i in range(1, n):
  
         # Find profit including the current job
-        inclProf = job[i].profit
-        l = binarySearch(job, i)
+        incl_prof = job[i].profit
+        l = binary_search(job, i)
         if (l != -1):
-            inclProf += table[l];
+            incl_prof += table[l];
  
         # Store maximum of including and excluding
-        table[i] = max(inclProf, table[i - 1])
+        table[i] = max(incl_prof, table[i - 1])
  
     return table[n-1]
diff --git a/dp/matrix_chain_order.py b/dp/matrix_chain_order.py
index 651079c..8c1ecae 100644
--- a/dp/matrix_chain_order.py
+++ b/dp/matrix_chain_order.py
@@ -7,11 +7,11 @@ Space Complexity: O(n^2)
 INF = float("inf")
 
 def matrix_chain_order(array):
-    N=len(array)
-    matrix = [[0 for x in range(N)] for x in range(N)]
-    sol = [[0 for x in range(N)] for x in range(N)]
-    for chain_length in range(2,N):
-        for a in range(1,N-chain_length+1):
+    n=len(array)
+    matrix = [[0 for x in range(n)] for x in range(n)]
+    sol = [[0 for x in range(n)] for x in range(n)]
+    for chain_length in range(2,n):
+        for a in range(1,n-chain_length+1):
             b = a+chain_length-1
 
             matrix[a][b] = INF
diff --git a/dp/min_cost_path.py b/dp/min_cost_path.py
index e346321..8af9470 100644
--- a/dp/min_cost_path.py
+++ b/dp/min_cost_path.py
@@ -27,17 +27,17 @@ INF = float("inf")
 
 def min_cost(cost):
  
-    N = len(cost)
+    n = len(cost)
     # dist[i] stores minimum cost from 0 --> i.
-    dist = [INF] * N
+    dist = [INF] * n
 
     dist[0] = 0   # cost from 0 --> 0 is zero.
   
-    for i in range(N):
-        for j in range(i+1,N):
+    for i in range(n):
+        for j in range(i+1,n):
             dist[j] = min(dist[j], dist[i] + cost[i][j])
   
-    return dist[N-1]
+    return dist[n-1]
 
 if __name__ == '__main__':
     
@@ -45,9 +45,9 @@ if __name__ == '__main__':
              [-1,  0, 40, 50],         # going from i --> j
              [-1, -1,  0, 70],         
              [-1, -1, -1,  0] ]        # cost[i][j] = -1 for i > j
-    N = len(cost)
+    total_len = len(cost)
     
     mcost = min_cost(cost)
     assert mcost == 65
     
-    print("The Minimum cost to reach station %d is %d" % (N, mcost))
+    print("The Minimum cost to reach station %d is %d" % (total_len, mcost))
diff --git a/dp/regex_matching.py b/dp/regex_matching.py
index e8449d4..78b13c6 100644
--- a/dp/regex_matching.py
+++ b/dp/regex_matching.py
@@ -21,7 +21,7 @@ isMatch("aab", "c*a*b") → true
 import unittest
 
 class Solution(object):
-    def isMatch(self, s, p):
+    def is_match(self, s, p):
         m, n = len(s) + 1, len(p) + 1
         matches = [[False] * n  for _ in range(m)]
 
diff --git a/dp/rod_cut.py b/dp/rod_cut.py
index 0272eee..b4a8224 100644
--- a/dp/rod_cut.py
+++ b/dp/rod_cut.py
@@ -3,7 +3,7 @@ INT_MIN = -32767
  
 # Returns the best obtainable price for a rod of length n and
 # price[] as prices of different pieces
-def cutRod(price):
+def cut_rod(price):
     n = len(price)
     val = [0]*(n+1)
  
@@ -19,6 +19,6 @@ def cutRod(price):
  
 # Driver program to test above functions
 arr = [1, 5, 8, 9, 10, 17, 17, 20]
-print("Maximum Obtainable Value is " + str(cutRod(arr)))
+print("Maximum Obtainable Value is " + str(cut_rod(arr)))
  
 # This code is contributed by Bhavya Jain
diff --git a/graph/minimum_spanning_tree.py b/graph/minimum_spanning_tree.py
index 2f47e39..2a877f9 100644
--- a/graph/minimum_spanning_tree.py
+++ b/graph/minimum_spanning_tree.py
@@ -22,7 +22,7 @@ class DisjointSet:
         for i in range(n):
             self.parent[i] = i # Make all nodes his own parent, creating n sets.
 
-    def mergeSet(self, a, b):
+    def merge_set(self, a, b):
         # Args:
         #   a, b (int): Indexes of nodes whose sets will be merged.
 
@@ -39,12 +39,12 @@ class DisjointSet:
             self.parent[b] = a # Merge set(b) and set(a)
             self.size[a] += self.size[b] # Add size of old set(b) to set(a)
 
-    def findSet(self, a):
+    def find_set(self, a):
         if self.parent[a] != a: 
             # Very important, memoize result of the 
             # recursion in the list to optimize next
             # calls and make this operation practically constant, O(1)
-            self.parent[a] = self.findSet(self.parent[a])
+            self.parent[a] = self.find_set(self.parent[a])
 
         # node <a> it's the set root, so we can return that index
         return self.parent[a]
@@ -76,7 +76,7 @@ def kruskal(n, edges, ds):
         set_u = ds.findSet(edge.u) # Set of the node <u>
         set_v = ds.findSet(edge.v) # Set of the node <v>
         if set_u != set_v:
-            ds.mergeSet(set_u, set_v)
+            ds.merge_set(set_u, set_v)
             mst.append(edge)
             if len(mst) == n-1: 
                 # If we have selected n-1 edges, all the other 
diff --git a/heap/binary_heap.py b/heap/binary_heap.py
index fc2f36a..24e52fc 100644
--- a/heap/binary_heap.py
+++ b/heap/binary_heap.py
@@ -51,7 +51,7 @@ class AbstractHeap(metaclass=ABCMeta):
     @abstractmethod
     def remove_min(self,i):
         pass
-class Binary_Heap(AbstractHeap):
+class BinaryHeap(AbstractHeap):
     def __init__(self):
         self.currentSize = 0
         self.heap = [(0)]
@@ -120,7 +120,7 @@ class TestSuite(unittest.TestCase):
         Test suite for the Binary_Heap data structures
     """
     def setUp(self):
-        self.min_heap = Binary_Heap()
+        self.min_heap = BinaryHeap()
         self.min_heap.insert(4)
         self.min_heap.insert(50)
         self.min_heap.insert(7)
diff --git a/heap/merge_sorted_k_lists.py b/heap/merge_sorted_k_lists.py
index 7406843..2fbfe1d 100644
--- a/heap/merge_sorted_k_lists.py
+++ b/heap/merge_sorted_k_lists.py
@@ -14,7 +14,7 @@ class ListNode(object):
         self.next = None
 
 
-def mergeKLists(lists):
+def merge_k_lists(lists):
     dummy = node = ListNode(0)
     h = [(n.val, n) for n in lists if n]
     heapify(h)
diff --git a/heap/skyline.py b/heap/skyline.py
index 73fb6e8..5912add 100644
--- a/heap/skyline.py
+++ b/heap/skyline.py
@@ -37,19 +37,19 @@ into one in the final output as such: [...[2 3], [4 5], [12 7], ...]
 
 import heapq
 
-def get_skyline(LRH):
+def get_skyline(lrh):
     """
     Wortst Time Complexity: O(NlogN)
     :type buildings: List[List[int]]
     :rtype: List[List[int]]
     """
     skyline, live = [], []
-    i, n = 0, len(LRH)
+    i, n = 0, len(lrh)
     while i < n or live:
-        if not live or i < n and LRH[i][0] <= -live[0][1]:
-            x = LRH[i][0]
-            while i < n and LRH[i][0] == x:
-                heapq.heappush(live, (-LRH[i][2], -LRH[i][1]))
+        if not live or i < n and lrh[i][0] <= -live[0][1]:
+            x = lrh[i][0]
+            while i < n and lrh[i][0] == x:
+                heapq.heappush(live, (-lrh[i][2], -lrh[i][1]))
                 i += 1
         else:
             x = -live[0][1]
diff --git a/linkedlist/is_palindrome.py b/linkedlist/is_palindrome.py
index 1256507..c9f2bc1 100644
--- a/linkedlist/is_palindrome.py
+++ b/linkedlist/is_palindrome.py
@@ -7,7 +7,7 @@ def is_palindrome(head):
         fast = fast.next.next
         slow = slow.next
     second = slow.next
-    slow.next = None # Don't forget here! But forget still works!
+    slow.next = None  # Don't forget here! But forget still works!
     # reverse the second part
     node = None
     while second:
@@ -24,6 +24,7 @@ def is_palindrome(head):
         head = head.next
     return True
 
+
 def is_palindrome_stack(head):
     if not head or not head.next:
         return True
@@ -80,7 +81,7 @@ def is_palindrome_dict(head):
         else:
             step = 0
             for i in range(0, len(v)):
-                if v[i] + v[len(v)-1-step] != checksum:
+                if v[i] + v[len(v) - 1 - step] != checksum:
                     return False
                 step += 1
         if middle > 1:
diff --git a/linkedlist/kth_to_last.py b/linkedlist/kth_to_last.py
index 48015a9..fb70a5c 100644
--- a/linkedlist/kth_to_last.py
+++ b/linkedlist/kth_to_last.py
@@ -62,7 +62,7 @@ def kth_to_last(head, k):
     return p2
 
 
-def printLinkedList(head):
+def print_linked_list(head):
     string = ""
     while head.next:
         string += head.val + " -> "
@@ -89,7 +89,7 @@ def test():
     d.next = c2
     c2.next = f
     f.next = g
-    printLinkedList(a1)
+    print_linked_list(a1)
 
     # test kth_to_last_eval
     kth = kth_to_last_eval(a1, 4)
diff --git a/linkedlist/partition.py b/linkedlist/partition.py
index ae6a2ba..8078f33 100644
--- a/linkedlist/partition.py
+++ b/linkedlist/partition.py
@@ -18,7 +18,7 @@ class Node():
         self.next = None
 
 
-def printLinkedList(head):
+def print_linked_list(head):
     string = ""
     while head.next:
         string += str(head.val) + " -> "
@@ -67,9 +67,9 @@ def test():
     e.next = f
     f.next = g
 
-    printLinkedList(a)
+    print_linked_list(a)
     partition(a, 5)
-    printLinkedList(a)
+    print_linked_list(a)
 
 
 if __name__ == '__main__':
diff --git a/linkedlist/remove_duplicates.py b/linkedlist/remove_duplicates.py
index a9f791c..ba18aec 100644
--- a/linkedlist/remove_duplicates.py
+++ b/linkedlist/remove_duplicates.py
@@ -3,7 +3,7 @@ class Node():
         self.val = val
         self.next = None
 
-def removeDups(head):
+def remove_dups(head):
     """
     Time Complexity: O(N)
     Space Complexity: O(N)
@@ -18,7 +18,7 @@ def removeDups(head):
             prev = head
         head = head.next
 
-def removeDupsWithoutSet(head):
+def remove_dups_wothout_set(head):
     """
     Time Complexity: O(N^2)
     Space Complexity: O(1)
@@ -33,7 +33,7 @@ def removeDupsWithoutSet(head):
                 runner = runner.next
         current = current.next
 
-def printLinkedList(head):
+def print_linked_list(head):
     string = ""
     while head.next:
         string += head.val + " -> "
@@ -60,7 +60,7 @@ d.next = c2
 c2.next = f
 f.next = g
 
-removeDups(a1)
-printLinkedList(a1)
-removeDupsWithoutSet(a1)
-printLinkedList(a1)
+remove_dups(a1)
+print_linked_list(a1)
+remove_dups_wothout_set(a1)
+print_linked_list(a1)
diff --git a/maths/generate_strobogrammtic.py b/maths/generate_strobogrammtic.py
index 2311dcf..dd0c400 100644
--- a/maths/generate_strobogrammtic.py
+++ b/maths/generate_strobogrammtic.py
@@ -34,7 +34,7 @@ def helper(n, length):
     return result
 
 
-def strobogrammaticInRange(low, high):
+def strobogrammatic_in_range(low, high):
     """
     :type low: str
     :type high: str
diff --git a/matrix/sparse_mul.py b/matrix/sparse_mul.py
index f87bcd2..c3b7b61 100644
--- a/matrix/sparse_mul.py
+++ b/matrix/sparse_mul.py
@@ -24,76 +24,76 @@ AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
 
 
 # Python solution without table (~156ms):
-def multiply(self, A, B):
+def multiply(self, a, b):
     """
     :type A: List[List[int]]
     :type B: List[List[int]]
     :rtype: List[List[int]]
     """
-    if A is None or B is None: return None
-    m, n, l = len(A), len(A[0]), len(B[0])
-    if len(B) != n:
+    if a is None or b is None: return None
+    m, n, l = len(a), len(b[0]), len(b[0])
+    if len(b) != n:
         raise Exception("A's column number must be equal to B's row number.")
-    C = [[0 for _ in range(l)] for _ in range(m)]
-    for i, row in enumerate(A):
+    c = [[0 for _ in range(l)] for _ in range(m)]
+    for i, row in enumerate(a):
         for k, eleA in enumerate(row):
             if eleA:
-                for j, eleB in enumerate(B[k]):
-                    if eleB: C[i][j] += eleA * eleB
-    return C
+                for j, eleB in enumerate(b[k]):
+                    if eleB: c[i][j] += eleA * eleB
+    return c
 
 
 # Python solution with only one table for B (~196ms):
-def multiply(self, A, B):
+def multiply(self, a, b):
     """
     :type A: List[List[int]]
     :type B: List[List[int]]
     :rtype: List[List[int]]
     """
-    if A is None or B is None: return None
-    m, n, l = len(A), len(A[0]), len(B[0])
-    if len(B) != n:
+    if a is None or b is None: return None
+    m, n, l = len(a), len(a[0]), len(b[0])
+    if len(b) != n:
         raise Exception("A's column number must be equal to B's row number.")
-    C = [[0 for _ in range(l)] for _ in range(m)]
-    tableB = {}
-    for k, row in enumerate(B):
-        tableB[k] = {}
+    c = [[0 for _ in range(l)] for _ in range(m)]
+    table_b = {}
+    for k, row in enumerate(b):
+        table_b[k] = {}
         for j, eleB in enumerate(row):
-            if eleB: tableB[k][j] = eleB
-    for i, row in enumerate(A):
+            if eleB: table_b[k][j] = eleB
+    for i, row in enumerate(a):
         for k, eleA in enumerate(row):
             if eleA:
-                for j, eleB in tableB[k].iteritems():
-                    C[i][j] += eleA * eleB
-    return C
+                for j, eleB in table_b[k].iteritems():
+                    c[i][j] += eleA * eleB
+    return c
 
 # Python solution with two tables (~196ms):
-def multiply(self, A, B):
+def multiply(self, a, b):
     """
     :type A: List[List[int]]
     :type B: List[List[int]]
     :rtype: List[List[int]]
     """
-    if A is None or B is None: return None
-    m, n = len(A), len(A[0])
-    if len(B) != n:
+    if a is None or b is None: return None
+    m, n = len(a), len(b[0])
+    if len(b) != n:
         raise Exception("A's column number must be equal to B's row number.")
-    l = len(B[0])
-    table_A, table_B = {}, {}
-    for i, row in enumerate(A):
+    l = len(b[0])
+    table_a, table_b = {}, {}
+    for i, row in enumerate(a):
         for j, ele in enumerate(row):
             if ele:
-                if i not in table_A: table_A[i] = {}
-                table_A[i][j] = ele
-    for i, row in enumerate(B):
+                if i not in table_a: table_a[i] = {}
+                table_a[i][j] = ele
+    for i, row in enumerate(b):
         for j, ele in enumerate(row):
             if ele:
-                if i not in table_B: table_B[i] = {}
-                table_B[i][j] = ele
-    C = [[0 for j in range(l)] for i in range(m)]
-    for i in table_A:
-        for k in table_A[i]:
-            if k not in table_B: continue
-            for j in table_B[k]:
-                C[i][j] += table_A[i][k] * table_B[k][j]
-    return C
+                if i not in table_b: table_b[i] = {}
+                table_b[i][j] = ele
+    c = [[0 for j in range(l)] for i in range(m)]
+    for i in table_a:
+        for k in table_a[i]:
+            if k not in table_b: continue
+            for j in table_b[k]:
+                c[i][j] += table_a[i][k] * table_b[k][j]
+    return c
diff --git a/sort/topsort.py b/sort/topsort.py
index 76cd43c..bca556d 100644
--- a/sort/topsort.py
+++ b/sort/topsort.py
@@ -23,22 +23,22 @@ depGraph = {
 
 given = [ "b", "c", "a", "d", "e", "f" ]
 
-def retDeps(visited, start):
+def ret_deps(visited, start):
     queue = []
     out = []
     queue.append(start)
     while queue:
-        newNode = queue.pop(0)
-        if newNode not in visited:
-            visited.add(newNode)
-        for child in depGraph[newNode]:
+        new_node = queue.pop(0)
+        if new_node not in visited:
+            visited.add(new_node)
+        for child in depGraph[new_node]:
             queue.append(child)
             out.append(child)
     out.append(start)
     return out
 
 
-def retDepGraph():
+def ret_dep_graph():
     visited = set()
     out = []
     # visited.add(given[0])
@@ -52,7 +52,7 @@ def retDepGraph():
             for child in depGraph[pac]:
                 if child in visited:
                     continue
-                out.extend(retDeps(visited, child))
+                out.extend(ret_deps(visited, child))
         out.append(pac)
     print(out)
-retDepGraph()
+ret_dep_graph()
diff --git a/strings/group_anagrams.py b/strings/group_anagrams.py
index 1bf3c0a..47441e4 100644
--- a/strings/group_anagrams.py
+++ b/strings/group_anagrams.py
@@ -13,7 +13,7 @@ Return:
 
 
 class Solution(object):
-    def groupAnagrams(self, strs):
+    def group_anagrams(self, strs):
         d = {}
         ans = []
         k = 0
diff --git a/strings/int_to_roman.py b/strings/int_to_roman.py
index dd25637..1da2012 100644
--- a/strings/int_to_roman.py
+++ b/strings/int_to_roman.py
@@ -8,10 +8,10 @@ def int_to_roman(num):
     :type num: int
     :rtype: str
     """
-    M = ["", "M", "MM", "MMM"];
-    C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
-    X = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
-    I = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
-    return M[num//1000] + C[(num%1000)//100] + X[(num%100)//10] + I[num%10];
+    m = ["", "M", "MM", "MMM"];
+    c = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
+    x = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"];
+    i = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
+    return m[num//1000] + c[(num%1000)//100] + x[(num%100)//10] + i[num%10];
 
 print(int_to_roman(644))
diff --git a/strings/license_number.py b/strings/license_number.py
index cbcb2d9..2d3a724 100644
--- a/strings/license_number.py
+++ b/strings/license_number.py
@@ -1,12 +1,12 @@
 
-def license_number(key, K):
+def license_number(key, k):
     res, alnum = [], []
     for char in key:
         if char != "-":
             alnum.append(char)
     for i, char in enumerate(reversed(alnum)):
         res.append(char)
-        if (i+1) % K == 0 and i != len(alnum)-1:
+        if (i+1) % k == 0 and i != len(alnum)-1:
             res.append("-")
     return "".join(res[::-1])
 
diff --git a/strings/rabin_karp.py b/strings/rabin_karp.py
index ca6a18a..51307db 100644
--- a/strings/rabin_karp.py
+++ b/strings/rabin_karp.py
@@ -2,20 +2,20 @@
 # Rabin Karp Algorithm
 
 class RollingHash:
-    def __init__(self, text, sizeWord):
+    def __init__(self, text, size_word):
         self.text = text
         self.hash = 0
-        self.sizeWord = sizeWord
+        self.sizeWord = size_word
 
-        for i in range(0, sizeWord):
+        for i in range(0, size_word):
             #ord maps the character to a number
             #subtract out the ASCII value of "a" to start the indexing at zero
-            self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(sizeWord - i -1))
+            self.hash += (ord(self.text[i]) - ord("a")+1)*(26**(size_word - i -1))
 
         #start index of current window
         self.window_start = 0
         #end of index window
-        self.window_end = sizeWord
+        self.window_end = size_word
 
     def move_window(self):
         if self.window_end <= len(self.text) - 1:
diff --git a/tree/binary_tree_paths.py b/tree/binary_tree_paths.py
index aad3276..3de72f7 100644
--- a/tree/binary_tree_paths.py
+++ b/tree/binary_tree_paths.py
@@ -1,14 +1,14 @@
-def binaryTreePaths(root):
+def binary_tree_paths(root):
     res = []
     if not root:
         return res
-    DFS(res, root, str(root.val))
+    dfs(res, root, str(root.val))
     return res
 
-def DFS(res, root, cur):
+def dfs(res, root, cur):
     if not root.left and not root.right:
         res.append(cur)
     if root.left:
-        DFS(res, root.left, cur+'->'+str(root.left.val))
+        dfs(res, root.left, cur+'->'+str(root.left.val))
     if root.right:
-        DFS(res, root.right, cur+'->'+str(root.right.val))
+        dfs(res, root.right, cur+'->'+str(root.right.val))
diff --git a/tree/bst/bst.py b/tree/bst/bst.py
index 05dc697..223b6b7 100644
--- a/tree/bst/bst.py
+++ b/tree/bst/bst.py
@@ -14,7 +14,7 @@ class Node(object):
         self.left = None
         self.right = None
 
-class bst(object):
+class BST(object):
     def __init__(self):
         self.root = None
 
@@ -115,7 +115,7 @@ class bst(object):
 
 class TestSuite(unittest.TestCase):
     def setUp(self):
-        self.tree = bst()
+        self.tree = BST()
         self.tree.insert(10)
         self.tree.insert(15)
         self.tree.insert(6)
diff --git a/tree/bst/delete_node.py b/tree/bst/delete_node.py
index 7ee827d..f86ecbc 100644
--- a/tree/bst/delete_node.py
+++ b/tree/bst/delete_node.py
@@ -38,7 +38,7 @@ Another valid answer is [5,2,6,null,4,null,7].
 """
 
 class Solution(object):
-    def deleteNode(self, root, key):
+    def delete_node(self, root, key):
         """
         :type root: TreeNode
         :type key: int
diff --git a/tree/bst/is_bst.py b/tree/bst/is_bst.py
index 74ef0a5..a132a5a 100644
--- a/tree/bst/is_bst.py
+++ b/tree/bst/is_bst.py
@@ -21,7 +21,7 @@ Binary tree [1,2,3], return false.
 """
 
 
-def is_BST(root):
+def is_bst(root):
     """
     :type root: TreeNode
     :rtype: bool
diff --git a/tree/bst/kth_smallest.py b/tree/bst/kth_smallest.py
index c2e511a..4996791 100644
--- a/tree/bst/kth_smallest.py
+++ b/tree/bst/kth_smallest.py
@@ -21,7 +21,7 @@ def kth_smallest(root, k):
 
 
 class Solution(object):
-    def kthSmallest(self, root, k):
+    def kth_smallest(self, root, k):
         """
         :type root: TreeNode
         :type k: int
@@ -51,4 +51,4 @@ if __name__ == '__main__':
     n2.left, n2.right = n4, n5
     n3.left, n3.right = n6, n7
     print(kth_smallest(n1, 2))
-    print(Solution().kthSmallest(n1, 2))
+    print(Solution().kth_smallest(n1, 2))
diff --git a/tree/longest_consecutive.py b/tree/longest_consecutive.py
index 3b1947f..fde962c 100644
--- a/tree/longest_consecutive.py
+++ b/tree/longest_consecutive.py
@@ -33,11 +33,11 @@ def longest_consecutive(root):
     if not root:
         return 0
     maxlen = 0
-    DFS(root, 0, root.val, maxlen)
+    dfs(root, 0, root.val, maxlen)
     return maxlen
 
 
-def DFS(root, cur, target, maxlen):
+def dfs(root, cur, target, maxlen):
     if not root:
         return
     if root.val == target:
@@ -45,5 +45,5 @@ def DFS(root, cur, target, maxlen):
     else:
         cur = 1
     maxlen = max(cur, maxlen)
-    DFS(root.left, cur, root.val+1, maxlen)
-    DFS(root.right, cur, root.val+1, maxlen)
+    dfs(root.left, cur, root.val+1, maxlen)
+    dfs(root.right, cur, root.val+1, maxlen)
diff --git a/tree/lowest_common_ancestor.py b/tree/lowest_common_ancestor.py
index 1702949..5c4016a 100644
--- a/tree/lowest_common_ancestor.py
+++ b/tree/lowest_common_ancestor.py
@@ -21,7 +21,7 @@ since a node can be a descendant of itself according to the LCA definition.
 """
 
 
-def LCA(root, p, q):
+def lca(root, p, q):
     """
     :type root: TreeNode
     :type p: TreeNode
@@ -30,8 +30,8 @@ def LCA(root, p, q):
     """
     if not root or root is p or root is q:
         return root
-    left = LCA(root.left, p, q)
-    right = LCA(root.right, p, q)
+    left = lca(root.left, p, q)
+    right = lca(root.right, p, q)
     if left and right:
         return root
     return left if left else right
diff --git a/tree/min_height.py b/tree/min_height.py
index ebb8f75..a3923d4 100644
--- a/tree/min_height.py
+++ b/tree/min_height.py
@@ -5,7 +5,7 @@ class Node():
         self.right = None
 
 
-def minDepth(self, root):
+def min_depth(self, root):
     """
     :type root: TreeNode
     :rtype: int
diff --git a/tree/path_sum2.py b/tree/path_sum2.py
index 22c8780..c989f9c 100644
--- a/tree/path_sum2.py
+++ b/tree/path_sum2.py
@@ -23,17 +23,17 @@ def path_sum(root, sum):
     if not root:
         return []
     res = []
-    DFS(root, sum, [], res)
+    dfs(root, sum, [], res)
     return res
 
-def DFS(root, sum, ls, res):
+def dfs(root, sum, ls, res):
     if not root.left and not root.right and root.val == sum:
         ls.append(root.val)
         res.append(ls)
     if root.left:
-        DFS(root.left, sum-root.val, ls+[root.val], res)
+        dfs(root.left, sum-root.val, ls+[root.val], res)
     if root.right:
-        DFS(root.right, sum-root.val, ls+[root.val], res)
+        dfs(root.right, sum-root.val, ls+[root.val], res)
 
 
 # DFS with stack
diff --git a/tree/pretty_print.py b/tree/pretty_print.py
index d50f26f..1e75647 100644
--- a/tree/pretty_print.py
+++ b/tree/pretty_print.py
@@ -11,11 +11,11 @@
 from __future__ import print_function
 
 
-def treePrint(tree):
+def tree_print(tree):
     for key in tree:
         print(key, end=' ')  # end=' ' prevents a newline character
-        treeElem = tree[key]  # multiple lookups is expensive, even amortized O(1)!
-        for subElem in treeElem:
+        tree_element = tree[key]  # multiple lookups is expensive, even amortized O(1)!
+        for subElem in tree_element:
             print(" -> ", subElem, end=' ')
             if type(subElem) != str:  # OP wants indenting after digits
                 print("\n ")  # newline and a space to match indenting
diff --git a/tree/same_tree.py b/tree/same_tree.py
index 9100c4f..a407f6f 100644
--- a/tree/same_tree.py
+++ b/tree/same_tree.py
@@ -7,11 +7,11 @@ structurally identical and the nodes have the same value.
 """
 
 
-def isSameTree(p, q):
+def is_same_tree(p, q):
     if not p and not q:
         return True
     if p and q and p.val == q.val:
-        return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
+        return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
     return False
 
 # Time Complexity O(min(N,M))
diff --git a/tree/segment_tree/segment_tree.py b/tree/segment_tree/segment_tree.py
index d9f0a69..de62b6b 100644
--- a/tree/segment_tree/segment_tree.py
+++ b/tree/segment_tree/segment_tree.py
@@ -3,7 +3,7 @@ Segment_tree creates a segment tree with a given array and function,
 allowing queries to be done later in log(N) time
 function takes 2 values and returns a same type value
 '''
-class segment_tree:
+class SegmentTree:
     def __init__(self,arr,function):
         self.segment = [0 for x in range(3*len(arr)+3)]
         self.arr = arr
@@ -38,11 +38,11 @@ class segment_tree:
 
 '''
 Example -
-mytree = segment_tree([2,4,5,3,4],max)
+mytree = SegmentTree([2,4,5,3,4],max)
 mytree.query(2,4)
 mytree.query(0,3) ...
 
-mytree = segment_tree([4,5,2,3,4,43,3],sum)
+mytree = SegmentTree([4,5,2,3,4,43,3],sum)
 mytree.query(1,8)
 ...
 
diff --git a/tree/trie/add_and_search.py b/tree/trie/add_and_search.py
index 70fb131..70f1e95 100644
--- a/tree/trie/add_and_search.py
+++ b/tree/trie/add_and_search.py
@@ -25,7 +25,7 @@ class WordDictionary(object):
     def __init__(self):
         self.root = TrieNode("")
 
-    def addWord(self, word):
+    def add_word(self, word):
         cur = self.root
         for letter in word:
             if letter not in cur.children:
@@ -60,7 +60,7 @@ class WordDictionary2(object):
         self.word_dict = collections.defaultdict(list)
 
 
-    def addWord(self, word):
+    def add_word(self, word):
         if word:
             self.word_dict[len(word)].append(word)
 
diff --git a/tree/trie/trie.py b/tree/trie/trie.py
index 19f35f1..6c56209 100644
--- a/tree/trie/trie.py
+++ b/tree/trie/trie.py
@@ -31,7 +31,7 @@ class Trie:
                 return False
         return current.is_word
 
-    def startsWith(self, prefix):
+    def starts_with(self, prefix):
         current = self.root
         for letter in prefix:
             current = current.children.get(letter)
diff --git a/union-find/count_islands.py b/union-find/count_islands.py
index 15cd676..56bed5b 100644
--- a/union-find/count_islands.py
+++ b/union-find/count_islands.py
@@ -38,7 +38,7 @@ Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
 
 
 class Solution(object):
-    def numIslands2(self, m, n, positions):
+    def num_islands2(self, m, n, positions):
         ans = []
         islands = Union()
         for p in map(tuple, positions):


Test patch:
diff --git a/tests/test_maths.py b/tests/test_maths.py
index 1e1ca64..631c0e1 100644
--- a/tests/test_maths.py
+++ b/tests/test_maths.py
@@ -1,9 +1,7 @@
-import unittest
-
 from maths.base_conversion import int2base, base2int
 from maths.extended_gcd import extended_gcd
 from maths.gcd import gcd, lcm
-from maths.generate_strobogrammtic import gen_strobogrammatic, strobogrammaticInRange
+from maths.generate_strobogrammtic import gen_strobogrammatic, strobogrammatic_in_range
 from maths.is_strobogrammatic import is_strobogrammatic, is_strobogrammatic2
 from maths.next_perfect_square import find_next_square, find_next_square2
 from maths.prime_test import prime_test
@@ -12,6 +10,8 @@ from maths.pythagoras import pythagoras
 from maths.rabin_miller import is_prime
 from maths.rsa import encrypt, decrypt, generate_key
 
+import unittest
+
 
 class TestBaseConversion(unittest.TestCase):
     """
@@ -72,8 +72,8 @@ class TestGenerateStroboGrammatic(unittest.TestCase):
     def test_gen_strobomatic(self):
         self.assertEqual(['88', '11', '96', '69'], gen_strobogrammatic(2))
 
-    def test_strobogrammaticInRange(self):
-        self.assertEqual(4, strobogrammaticInRange("10", "100"))
+    def test_strobogrammatic_in_range(self):
+        self.assertEqual(4, strobogrammatic_in_range("10", "100"))
 
 
 class TestIsStrobogrammatic(unittest.TestCase):
@@ -200,5 +200,6 @@ class TestRSA(unittest.TestCase):
     #         dec = decrypt(en, d, n)
     #         self.assertEqual(data,dec)
 
+
 if __name__ == "__main__":
     unittest.main()