From fd6f80afe3650bdb77f01352d9f4da397fd133ea Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Fri, 18 Oct 2019 01:42:23 +0530 Subject: [PATCH 01/12] Another method added for GCD --- maths/greatest_common_divisor.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index ebc08f37ffa6..4006c661550e 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -5,6 +5,15 @@ """ + +# This method is more efficient not acquire more memory cause is no use of any stacks like in recursive as next below mentioned. +def gcd_by_iterative(x,y): + while y:x,y=y,x%y + + return x + + + def gcd(a, b): """Calculate Greatest Common Divisor (GCD).""" return b if a == 0 else gcd(b % a, a) @@ -16,10 +25,14 @@ def main(): nums = input("Enter two Integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) + print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") + print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") + except (IndexError, UnboundLocalError, ValueError): print("Wrong Input") - + if __name__ == "__main__": main() + From c9630ef0ac1aa22df4fd089ac6ed3952d61559fa Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Fri, 18 Oct 2019 10:41:54 +0530 Subject: [PATCH 02/12] Now doctest fulfilled for added method. --- maths/greatest_common_divisor.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index 4006c661550e..5b9c95078797 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -5,13 +5,6 @@ """ - -# This method is more efficient not acquire more memory cause is no use of any stacks like in recursive as next below mentioned. -def gcd_by_iterative(x,y): - while y:x,y=y,x%y - - return x - def gcd(a, b): @@ -19,6 +12,19 @@ def gcd(a, b): return b if a == 0 else gcd(b % a, a) +""" +This method is more efficient. +This method is not acquire more memory cause is no use of any stacks(chunk of a memory space). +while above method is good one but acquire more memory for huge number because of more recursive call. + +""" +def gcd_by_iterative(x,y): + while y: + x,y=y,x%y + """Now return final answer that is GCD""" + return x + + def main(): """Call GCD Function.""" try: From 70ed30df9a1dd1dd59031d48df72a0af2c7232a6 Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Fri, 18 Oct 2019 12:27:53 +0530 Subject: [PATCH 03/12] Update greatest_common_divisor.py --- maths/greatest_common_divisor.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index 5b9c95078797..d6a06a4abc30 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -2,10 +2,7 @@ Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor -""" - - - +""" def gcd(a, b): """Calculate Greatest Common Divisor (GCD).""" @@ -13,7 +10,7 @@ def gcd(a, b): """ -This method is more efficient. +Below method is more efficient. This method is not acquire more memory cause is no use of any stacks(chunk of a memory space). while above method is good one but acquire more memory for huge number because of more recursive call. @@ -24,7 +21,6 @@ def gcd_by_iterative(x,y): """Now return final answer that is GCD""" return x - def main(): """Call GCD Function.""" try: @@ -37,8 +33,7 @@ def main(): except (IndexError, UnboundLocalError, ValueError): print("Wrong Input") - - + if __name__ == "__main__": main() From da5ad7b2a964f6217de1b8ca51044bc7b9e8074a Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Fri, 18 Oct 2019 12:37:11 +0530 Subject: [PATCH 04/12] Now unnecessary white spaces removed. --- maths/greatest_common_divisor.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index d6a06a4abc30..ced8142db1a5 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -2,8 +2,7 @@ Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor -""" - +""" def gcd(a, b): """Calculate Greatest Common Divisor (GCD).""" return b if a == 0 else gcd(b % a, a) @@ -12,7 +11,7 @@ def gcd(a, b): """ Below method is more efficient. This method is not acquire more memory cause is no use of any stacks(chunk of a memory space). -while above method is good one but acquire more memory for huge number because of more recursive call. +while above method is good one but acquire more memory for huge number because of more recursive call to evaluate GCD. """ def gcd_by_iterative(x,y): From e29cf99c66c3cb64eb0380c66a7e98fe97160b59 Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Sat, 19 Oct 2019 11:53:14 +0530 Subject: [PATCH 05/12] Cycle_Detection_Undirected_Graph Cycle_Detection_Undirected_Graph using Disjoint set DataStructure --- graphs/Cycle_Detection_Undirected_Graph.py | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 graphs/Cycle_Detection_Undirected_Graph.py diff --git a/graphs/Cycle_Detection_Undirected_Graph.py b/graphs/Cycle_Detection_Undirected_Graph.py new file mode 100644 index 000000000000..595e31fe547f --- /dev/null +++ b/graphs/Cycle_Detection_Undirected_Graph.py @@ -0,0 +1,108 @@ +#Contributed by : Ghulam Mohiyuddin +""" +what is this: Here I am going to detect cycle in graph,return 1 if any otherwise 0. + +Data Structure Used: + DisJoint Set (Union, parent) + Dictionary + List + + +link:https://en.wikipedia.org/wiki/Disjoint-set_data_structure + + +Input style: + The First line of each testcase contains two integers 'N' and 'M' which denotes the no of vertices and no of edges respectively. + The Second line of each test case contains 'M' space separated pairs u and v denoting that there is a bidirectional edge from u to v + + eg-1: + 5 4 #--------->No. of nodes is5, and edges is 4. + 0 1 2 3 3 4 4 2 #--------->edges are (0<-->1),(2<-->3),(3<-->4) and (4<-->2). + Output: 1 #----> 1 means cycle exist. + + + eg 2: + 4 3 #--------->No. of nodes is 4, and edges is 3. + 0 1 1 2 2 3 #--------->edges are (0<-->1),(1<-->2) and (2<-->3). + Output: 0 #----->0 means not exist. + + + +""" + + +from collections import defaultdict + +#Graph Class: +class Graph(): + def __init__(self,vertices): + self.graph = defaultdict(list)# Initialize + + self.V = vertices # Initialize no. of vertices + + + def addEdge(self,u,v): # add directed edge from u to v. + self.graph[u].append(v) + + + + +def union(parentA,d,e): + x_=parent(parentA,d) + y_=parent(parentA,e) + parentA[x_]=y_ + +def parent(parentA,k): + if parentA[k]==-1: + return k + return parent(parentA,parentA[k]) + + +def isCyclic(g,n): + ''' + :param g: given adjacency list representation of graph + :param n: no of nodes in graph + + ''' + # code here + visit={i:False for i in range(n)}# dictionary for trace a node is visited or not by true or false + parentA=[-1]*n + + for i in g: + for j in g[i]: + if visit[j]==False: + + x=parent(parentA,i) + y=parent(parentA,j) + #print(i,x,j,y) + if x==y: + #return 1 if any + + return 1 + union(parentA,i,j) + visit[i]=True + + #return 0 if not cycle + return 0 + + + + + + +if __name__ == '__main__': + #test_cases = int(input()) + #for cases in range(test_cases) : + N,E = map(int,input().strip().split()) #N=5,E=4(pair of u,v) + + g = Graph(N)# make an object of Graph Class + edges = list(map(int,input().strip().split())) + for i in range(0,len(edges),2): + u,v = edges[i],edges[i+1] + g.addEdge(u,v) # add an undirected edge from u to v + g.addEdge(v,u)# add an undirected edge from v to u + print(isCyclic(g.graph,N)) + + + + From 5857599712cc0e00e2bf374962c8a3778bceba1a Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Sun, 20 Oct 2019 23:35:34 +0530 Subject: [PATCH 06/12] Update greatest_common_divisor.py again --- maths/greatest_common_divisor.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index ced8142db1a5..786292fecdf6 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -15,10 +15,9 @@ def gcd(a, b): """ def gcd_by_iterative(x,y): - while y: + while y: #-->when y=0 then loop will terminate and return x as final GCD. x,y=y,x%y - """Now return final answer that is GCD""" - return x + return x def main(): """Call GCD Function.""" From 4cb4de94455b3a43cd3c34ee2db2f2fbdc34a2ec Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Mon, 21 Oct 2019 00:14:19 +0530 Subject: [PATCH 07/12] Again Updated cycle_detection_undirected_graph.py --- ...py => cycle_detection_undirected_graph.py} | 50 ++++++++++++------- 1 file changed, 31 insertions(+), 19 deletions(-) rename graphs/{Cycle_Detection_Undirected_Graph.py => cycle_detection_undirected_graph.py} (56%) diff --git a/graphs/Cycle_Detection_Undirected_Graph.py b/graphs/cycle_detection_undirected_graph.py similarity index 56% rename from graphs/Cycle_Detection_Undirected_Graph.py rename to graphs/cycle_detection_undirected_graph.py index 595e31fe547f..82ffc3febf2b 100644 --- a/graphs/Cycle_Detection_Undirected_Graph.py +++ b/graphs/cycle_detection_undirected_graph.py @@ -1,16 +1,13 @@ #Contributed by : Ghulam Mohiyuddin """ -what is this: Here I am going to detect cycle in graph,return 1 if any otherwise 0. +What's this: Here I am going to detect cycle in graph,return 1 if any otherwise 0. Data Structure Used: - DisJoint Set (Union, parent) + DisJoint Set (Union, parent)-link:https://en.wikipedia.org/wiki/Disjoint-set_data_structure Dictionary List -link:https://en.wikipedia.org/wiki/Disjoint-set_data_structure - - Input style: The First line of each testcase contains two integers 'N' and 'M' which denotes the no of vertices and no of edges respectively. The Second line of each test case contains 'M' space separated pairs u and v denoting that there is a bidirectional edge from u to v @@ -19,6 +16,22 @@ 5 4 #--------->No. of nodes is5, and edges is 4. 0 1 2 3 3 4 4 2 #--------->edges are (0<-->1),(2<-->3),(3<-->4) and (4<-->2). Output: 1 #----> 1 means cycle exist. + + + The following graph has a cycle 2-3-4-2 + 0---------1\ + '\ + 2, + / '\ + | 3, + | / + | / + | /' + 4 + + + + eg 2: @@ -36,12 +49,12 @@ #Graph Class: class Graph(): def __init__(self,vertices): - self.graph = defaultdict(list)# Initialize + self.graph = defaultdict(list) # Initialize - self.V = vertices # Initialize no. of vertices + self.V = vertices # Initialize no. of vertices - def addEdge(self,u,v): # add directed edge from u to v. + def addEdge(self,u,v): # add directed edge from u to v. self.graph[u].append(v) @@ -64,8 +77,8 @@ def isCyclic(g,n): :param n: no of nodes in graph ''' - # code here - visit={i:False for i in range(n)}# dictionary for trace a node is visited or not by true or false + + visit={i:False for i in range(n)} # dictionary for trace a node is visited or not by true or false parentA=[-1]*n for i in g: @@ -74,16 +87,15 @@ def isCyclic(g,n): x=parent(parentA,i) y=parent(parentA,j) - #print(i,x,j,y) - if x==y: - #return 1 if any - + + if x==y: return 1 + union(parentA,i,j) visit[i]=True - #return 0 if not cycle - return 0 + + return 0 #return 0 if not cycle @@ -93,14 +105,14 @@ def isCyclic(g,n): if __name__ == '__main__': #test_cases = int(input()) #for cases in range(test_cases) : - N,E = map(int,input().strip().split()) #N=5,E=4(pair of u,v) + N,E = map(int,input().strip().split()) #N=5,E=4(pair of u,v) g = Graph(N)# make an object of Graph Class edges = list(map(int,input().strip().split())) for i in range(0,len(edges),2): u,v = edges[i],edges[i+1] - g.addEdge(u,v) # add an undirected edge from u to v - g.addEdge(v,u)# add an undirected edge from v to u + g.addEdge(u,v) # add an undirected edge from u to v + g.addEdge(v,u) # add an undirected edge from v to u print(isCyclic(g.graph,N)) From dc102f4a99ca2f4bbb86c15afa1bf11b7af44529 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 22 Oct 2019 11:04:48 +0200 Subject: [PATCH 08/12] Delete cycle_detection_undirected_graph.py --- graphs/cycle_detection_undirected_graph.py | 120 --------------------- 1 file changed, 120 deletions(-) delete mode 100644 graphs/cycle_detection_undirected_graph.py diff --git a/graphs/cycle_detection_undirected_graph.py b/graphs/cycle_detection_undirected_graph.py deleted file mode 100644 index 82ffc3febf2b..000000000000 --- a/graphs/cycle_detection_undirected_graph.py +++ /dev/null @@ -1,120 +0,0 @@ -#Contributed by : Ghulam Mohiyuddin -""" -What's this: Here I am going to detect cycle in graph,return 1 if any otherwise 0. - -Data Structure Used: - DisJoint Set (Union, parent)-link:https://en.wikipedia.org/wiki/Disjoint-set_data_structure - Dictionary - List - - -Input style: - The First line of each testcase contains two integers 'N' and 'M' which denotes the no of vertices and no of edges respectively. - The Second line of each test case contains 'M' space separated pairs u and v denoting that there is a bidirectional edge from u to v - - eg-1: - 5 4 #--------->No. of nodes is5, and edges is 4. - 0 1 2 3 3 4 4 2 #--------->edges are (0<-->1),(2<-->3),(3<-->4) and (4<-->2). - Output: 1 #----> 1 means cycle exist. - - - The following graph has a cycle 2-3-4-2 - 0---------1\ - '\ - 2, - / '\ - | 3, - | / - | / - | /' - 4 - - - - - - - eg 2: - 4 3 #--------->No. of nodes is 4, and edges is 3. - 0 1 1 2 2 3 #--------->edges are (0<-->1),(1<-->2) and (2<-->3). - Output: 0 #----->0 means not exist. - - - -""" - - -from collections import defaultdict - -#Graph Class: -class Graph(): - def __init__(self,vertices): - self.graph = defaultdict(list) # Initialize - - self.V = vertices # Initialize no. of vertices - - - def addEdge(self,u,v): # add directed edge from u to v. - self.graph[u].append(v) - - - - -def union(parentA,d,e): - x_=parent(parentA,d) - y_=parent(parentA,e) - parentA[x_]=y_ - -def parent(parentA,k): - if parentA[k]==-1: - return k - return parent(parentA,parentA[k]) - - -def isCyclic(g,n): - ''' - :param g: given adjacency list representation of graph - :param n: no of nodes in graph - - ''' - - visit={i:False for i in range(n)} # dictionary for trace a node is visited or not by true or false - parentA=[-1]*n - - for i in g: - for j in g[i]: - if visit[j]==False: - - x=parent(parentA,i) - y=parent(parentA,j) - - if x==y: - return 1 - - union(parentA,i,j) - visit[i]=True - - - return 0 #return 0 if not cycle - - - - - - -if __name__ == '__main__': - #test_cases = int(input()) - #for cases in range(test_cases) : - N,E = map(int,input().strip().split()) #N=5,E=4(pair of u,v) - - g = Graph(N)# make an object of Graph Class - edges = list(map(int,input().strip().split())) - for i in range(0,len(edges),2): - u,v = edges[i],edges[i+1] - g.addEdge(u,v) # add an undirected edge from u to v - g.addEdge(v,u) # add an undirected edge from v to u - print(isCyclic(g.graph,N)) - - - - From 18260279eea552bce9e376a3334c5279ce55f2b3 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 22 Oct 2019 11:12:49 +0200 Subject: [PATCH 09/12] Add doctests and format the code with psf/black --- maths/greatest_common_divisor.py | 45 ++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index 786292fecdf6..caf2a57c6950 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -2,36 +2,49 @@ Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor -""" +""" + + def gcd(a, b): - """Calculate Greatest Common Divisor (GCD).""" + """ + Calculate Greatest Common Divisor (GCD). + >>> gcd(24, 40) + 8 + """ return b if a == 0 else gcd(b % a, a) """ Below method is more efficient. -This method is not acquire more memory cause is no use of any stacks(chunk of a memory space). -while above method is good one but acquire more memory for huge number because of more recursive call to evaluate GCD. - +This method is not acquire more memory cause is no use of any stacks(chunk of a memory +space). While above method is good one but acquire more memory for huge number because +of more recursive call to evaluate GCD. """ -def gcd_by_iterative(x,y): - while y: #-->when y=0 then loop will terminate and return x as final GCD. - x,y=y,x%y - return x + + +def gcd_by_iterative(x, y): + """ + >>> gcd_by_iterative(24, 40) + 8 + >>> gcd(24, 40) == gcd_by_iterative(24, 40) + True + """ + while y: # --> when y=0 then loop will terminate and return x as final GCD. + x, y = y, x % y + return x + def main(): - """Call GCD Function.""" + """Call GCD gunction.""" try: - nums = input("Enter two Integers separated by comma (,): ").split(",") + nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) - print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") - except (IndexError, UnboundLocalError, ValueError): - print("Wrong Input") - + print("Wrong input") + + if __name__ == "__main__": main() - From b435abb95523e5ce4b33f2485e15430f29b70742 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 22 Oct 2019 11:13:31 +0200 Subject: [PATCH 10/12] fixup: Typo --- maths/greatest_common_divisor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index caf2a57c6950..f7b398d13bca 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -35,7 +35,7 @@ def gcd_by_iterative(x, y): def main(): - """Call GCD gunction.""" + """Call GCD function.""" try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) From 60aeb5103f588d80f6001b97f9821480992f16c5 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 22 Oct 2019 11:20:24 +0200 Subject: [PATCH 11/12] Update greatest_common_divisor.py --- maths/greatest_common_divisor.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index f7b398d13bca..18099963dfb1 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -5,20 +5,19 @@ """ -def gcd(a, b): +def greatest_common_divisor(a, b): """ Calculate Greatest Common Divisor (GCD). - >>> gcd(24, 40) + >>> greatest_common_divisor(24, 40) 8 """ return b if a == 0 else gcd(b % a, a) """ -Below method is more efficient. -This method is not acquire more memory cause is no use of any stacks(chunk of a memory -space). While above method is good one but acquire more memory for huge number because -of more recursive call to evaluate GCD. +Below method is more memory efficient because it does not use the stack (chunk of memory). +While above method is good, uses more memory for huge numbers because of the recursive calls +required to calculate the greatest common divisor. """ @@ -26,7 +25,7 @@ def gcd_by_iterative(x, y): """ >>> gcd_by_iterative(24, 40) 8 - >>> gcd(24, 40) == gcd_by_iterative(24, 40) + >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True """ while y: # --> when y=0 then loop will terminate and return x as final GCD. @@ -35,12 +34,12 @@ def gcd_by_iterative(x, y): def main(): - """Call GCD function.""" + """Call Greatest Common Divisor function.""" try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) - print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") + print(f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}") print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") From 5a96d12940240a6d8bc0b6f3c4e3ffd03a297074 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Tue, 22 Oct 2019 11:22:58 +0200 Subject: [PATCH 12/12] greatest_common_divisor() --- maths/greatest_common_divisor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index 18099963dfb1..a1b915bc3cfb 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -11,7 +11,7 @@ def greatest_common_divisor(a, b): >>> greatest_common_divisor(24, 40) 8 """ - return b if a == 0 else gcd(b % a, a) + return b if a == 0 else greatest_common_divisor(b % a, a) """