Skip to content

Commit 5925786

Browse files
committed
add data structures folder
1 parent e649690 commit 5925786

File tree

4 files changed

+102
-0
lines changed

4 files changed

+102
-0
lines changed
File renamed without changes.
File renamed without changes.

data_structures/binary_tree.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#!/bin/python3
2+
import time
3+
start = time.time()
4+
5+
class Node:
6+
def __init__(self, data):
7+
self.left = None
8+
self.right = None
9+
self.data = data
10+
11+
def PrintTree(self):
12+
if self.left:
13+
self.left.PrintTree()
14+
print(self.data)
15+
if self.right:
16+
self.right.PrintTree()
17+
18+
def insert(self, data):
19+
if self.data:
20+
if data < self.data:
21+
if self.left is None:
22+
self.left = Node(data)
23+
return
24+
else:
25+
self.left.insert(data)
26+
elif data > self.data:
27+
if self.right is None:
28+
self.right = Node(data)
29+
return
30+
else:
31+
self.right.insert(data)
32+
else:
33+
self.data = data
34+
35+
def search_value(self, data):
36+
if self.data == data:
37+
print("value {} is found".format(data))
38+
return
39+
elif data < self.data:
40+
if self.left:
41+
return self.left.search_value(data)
42+
else:
43+
print("value {} does not exist!".format(data))
44+
return
45+
else:
46+
if self.right:
47+
return self.right.search_value(data)
48+
else:
49+
print("value {} does not exist!".format(data))
50+
return
51+
52+
53+
root = Node(12)
54+
root.insert(6)
55+
root.insert(14)
56+
root.insert(3)
57+
root.PrintTree()
58+
root.search_value(18)
59+
60+
print('Execution time:', time.time()-start, 'seconds.')
61+
62+

data_structures/graph.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class graph:
2+
def __init__(self, gdict=None):
3+
if gdict is None:
4+
gdict =[]
5+
self.gdict = gdict
6+
7+
def getVertices(self):
8+
return list(self.gdict.keys())
9+
10+
def getEdges(self):
11+
edges = []
12+
for vtx in self.gdict:
13+
for edg in self.gdict[vtx]:
14+
if {vtx, edg} not in edges:
15+
edges.append({vtx, edg})
16+
return edges
17+
18+
def addVertex(self, vxt):
19+
if vxt not in self.gdict:
20+
self.gdict[vxt] = []
21+
22+
def addEdge(self, edge):
23+
v1, v2 = tuple(edge)
24+
if v2 not in self.gdict[v1]:
25+
self.gdict[v1].append(v2)
26+
27+
28+
graph_elements = { "a" : ["b","c"],
29+
"b" : ["a", "d"],
30+
"c" : ["a", "d"],
31+
"d" : ["e"],
32+
"e" : ["d"]
33+
}
34+
35+
g = graph(graph_elements)
36+
37+
g.addVertex('f')
38+
g.addEdge({'a','e'})
39+
print(g.getVertices())
40+
print(g.getEdges())

0 commit comments

Comments
 (0)