Sure! Here's a simple implementation of a hash table in Python:
class HashTable():
def __init__(self, size=10):
self.size = size
self.keys = [None] * self.size
self.values = [None] * self.size
def hash_function(self, key):
return hash(key) % self.size
def insert(self, key, value):
i = self.hash_function(key)
while self.keys[i] is not None:
if self.keys[i] == key:
self.values[i] = value
return
i = (i + 1) % self.size
self.keys[i] = key
self.values[i] = value
def get(self, key):
i = self.hash_function(key)
while self.keys[i] is not None:
if self.keys[i] == key:
return self.values[i]
i = (i + 1) % self.size
return None
def __str__(self):
items = []
for k, v in zip(self.keys, self.values):
if k is not None:
items.append(f"{k}: {v}")
return "{" + ", ".join(items) + "}"
User
write me Breadth-first traversal python program
Assistant
Sure! Here's a basic implementation of Breadth-first traversal in Python:
from collections import deque
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def BFS(start_node, graph):
visited = set()
queue = deque([start_node])
while queue:
node = queue.popleft()
if node not in visited:
print(node, end=' ')
visited.add(node)
neighbours = graph[node]
for neighbour in neighbours:
queue.append(neighbour)
BFS('A', graph)
In this implementation, we first define a graph as a dictionary of nodes and their adjacent nodes. We then define a BFS function which takes a starting node and the graph as input.
We initialize a set called visited to keep track of the nodes we have already visited. We also create a deque called to hold the nodes that we want to visit next, starting with the starting node.
User
write me Depth-first traversal python program
Assistant
Sure! Here's a basic implementation of Depth-first traversal in Python:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def DFS(node, graph, visited=None):
if visited is None:
visited = set()
visited.add(node)
print(node, end=' ')
for neighbour in graph[node]:
if neighbour not in visited:
DFS(neighbour, graph, visited)
DFS('A', graph)
In this implementation, we first define a graph as a dictionary of nodes and their adjacent nodes. We then define a recursive DFS function which takes a node, the graph, and a set called visited (which keeps track of the nodes we have already visited) as input.
If visited is not already initialized (if it is None), we initialize it to an empty set. We then add the current node to the visited set and print it.
We then loop over the neighbours of the current node from the graph and call the DFS function recursively on any neighbours that have not already been visited. This ensures that we visit all the nodes in the graph.
User
write me a Breadth-first search algorithm python program
Assistant
Sure! Here's a basic implementation of Breadth-first search algorithm in Python:
from collections import deque
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def BFS(start_node, graph, target):
visited = set()
queue = deque([(start_node, [])])
while queue:
node, path = queue.popleft()
if node == target:
return path + [node]
if node not in visited:
visited.add(node)
for neighbour in graph[node]:
queue.append((neighbour, path + [node]))
return None
print(BFS('A', graph, 'F'))
User
write me . Depth-first search algorithm python program
Assistant
Sure! Here's a basic implementation of Depth-first search algorithm in Python:
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def DFS(start_node, graph, target, visited=None, path=None):
if visited is None:
visited = set()
if path is None:
path = []
visited.add(start_node)
path = path + [start_node]
if start_node == target:
return path
for neighbour in graph[start_node]:
if neighbour not in visited:
new_path = DFS(neighbour, graph, target, visited, path)
if new_path is not None:
return new_path
return None
print(DFS('A', graph, 'F'))
User
write me Shortest path algorithm python program
Assistant
User
write me Topological sorting algorithm python program
Assistant
Sure! Here's a basic implementation of Topological sorting algorithm in Python:
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
def add_edge(self, u, v):
self.graph[u].append(v)
def topological_sort_util(self, node, visited, stack):
visited.add(node)
for neighbour in self.graph[node]:
if neighbour not in visited:
self.topological_sort_util(neighbour, visited, stack)
stack.append(node)
def topological_sort(self):
visited = set()
stack = []
for node in self.vertices:
if node not in visited:
self.topological_sort_util(node, visited, stack)
return stack[::-1]
g = Graph(['A', 'B', 'C', 'D'])
g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')
print(g.topological_sort())
User
write me Bubble chart python program
Assistant
Sure! Here's a simple implementation of a bubble chart in Python using Matplotlib library:
import matplotlib.pyplot as plt
import random
x = [random.randint(0, 50) for i in range(30)] # x-axis values
y = [random.randint(0, 50) for i in range(30)] # y-axis values
z = [random.randint(0, 50) for i in range(30)] # sizes of the bubbles
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, s=z, alpha=0.5, edgecolors='none')
ax.grid(True)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Bubble Chart')
plt.show()
In this implementation, we first import the Matplotlib library. We then generate random values for the x-axis and y-axis coordinates, and the sizes (z) of the bubbles.
We create a figure and axes using the subplots function. We then create a scatter plot using the x-axis, y-axis, and bubble size data, by calling ax.scatter. We set the alpha value to 0.5 to make the bubbles semi-transparent, so that overlapping bubbles are visible. We also set the edgecolors to 'none', so that the bubbles have no outline.
User
write me Bubble chart data structure python program
Assistant
Sure! Here's an example implementation of the Bubble chart data structure in Python:
class Bubble:
def __init__(self, x=0, y=0, z=0, label=None, color=None):
self.x = x
self.y = y
self.z = z
self.label = label
self.color = color
class BubbleChart:
def __init__(self):
self.bubbles = []
def add_bubble(self, bubble):
self.bubbles.append(bubble)
def remove_bubble(self, bubble):
self.bubbles.remove(bubble)
def get_bubbles(self):
return self.bubbles
def get_x_values(self):
return [bubble.x for bubble in self.bubbles]
def get_y_values(self):
return [bubble.y for bubble in self.bubbles]
def get_z_values(self):
return [bubble.z for bubble in self.bubbles]
def clear(self):
self.bubbles = []
In this implementation, we use a hash function to map each key to an index in the keys and values arrays. If there are collisions (i.e., multiple keys map to the same index), we use linear probing to find the next available index. The insert method inserts a key-value pair into the table, the get method retrieves the value associated with a key, and the __str__ method provides a string representation of the table.
queue
We then enter a loop that continues until there are no more nodes in the queue. We use the popleft method to remove the first node from the queue and assign it to node.
We then check if node is in visited. If it is not, we print node, add it to the visited set, and get its neighbours from the graph. We then iterate over these neighbours and add them to the queue.
The final output of the BFS function is a breadth-first traversal of the graph starting from the starting node.
The final output of the DFS function is a depth-first traversal of the graph starting from the specified node.
In this implementation, we first define a graph as a dictionary of nodes and their adjacent nodes. We then define a BFS function which takes a starting node, the graph, and a target node as input.
We initialize a set called visited to keep track of the nodes we have already visited. We also create a deque called queue to hold the nodes that we want to visit next. In the queue, we will store a tuple where the first element is the current node and the second element is the path from the starting node to the current node.
We then enter a loop that continues until there are no more nodes in the queue. We use the popleft method to remove the first element of the queue (i.e., the tuple with the current node and its path), and assign it to node and path.
If the current node is the target node, we return the path from the starting node to the target node.
We then check if node is in visited. If it is not, we add it to the visited set, and get its neighbours from the graph. We then iterate over these neighbours and add them to the queue, but with their paths updated to include the current node.
If we have exhausted all possible paths without finding the target node, we return None.
The final output of the BFS function is a path from the starting node to the target node (if one exists).
In this implementation, we first define a graph as a dictionary of nodes and their adjacent nodes. We then define a recursive DFS function which takes a starting node, the graph, a target node, a set called visited (which keeps track of the nodes we have already visited), and a list called path (which keeps track of the current path from the starting node to the current node) as input.
If visited and path are not already initialized (if they are None), we initialize them to an empty set and an empty list, respectively. We then add the current node to the visited set and path.
If the current node is the target node, we return the path from the starting node to the target node.
We then loop over the neighbours of the current node from the graph and call the DFS function recursively on any neighbours that have not already been visited. We update the path with the current node and the new neighbour, and if the new path is not None, we return it.
If we have exhausted all possible paths without finding the target node, we return None.
The final output of the DFS function is a path from the starting node to the target node (if one exists).
Sure! Here's a basic implementation of Dijkstra's shortest path algorithm in Python:
In this implementation, we first define a graph as a dictionary of nodes and their adjacent nodes, along with the weights of the edges connecting them. We then define a dijkstra function which takes the graph, a start node, and an end node as input.
We initialize a dictionary called distances to keep track of the shortest distances from the start node to each node in the graph. We set all distances to infinity except for the start node, which we set to 0. We also create a priority queue (pq) which will hold the nodes with their minimum distance from the start_node. We also initialize a set calling it visited.
We then enter a loop that continues until the priority queue pq is empty or we have reached the end node. In each iteration, we extract the node with the smallest distance from the priority queue pq, using heappop.
We then check if the current node is the end node. If so, we return its shortest distance. We also check if the current node has already been visited. If it has, we continue to the next iteration of the loop.
We add the current node to the visited set and then iterate over its neighbours. For each neighbour, we calculate its distance from the start node via the current node, and update the distances dictionary if this new distance is lower than the previously known shortest distance. We then add the neighbour to the priority queue pq with its updated distance.
If we have exhausted all possible paths without reaching the end node, we return None.
The final output of the dijkstra function is the shortest distance from the start node to the end node.
In this implementation, we first define a class called Graph that has a dictionary called graph to hold the edges, and a list called vertices to hold the nodes.
We then define a method add_edge to add an edge to the graph.
We define a recursive method topological_sort_util that takes a node, a set called visited (which keeps track of the nodes we have already visited), and a stack to hold the sorted nodes. In this method, we iterate over the neighbours of the current node and recursively call topological_sort_util on any neighbours that have not already been visited. Once all the neighbours have been visited, we append the current node to the stack.
We then define a method topological_sort that loops over all the nodes in the graph and calls topological_sort_util on any nodes that have not already been visited. We return the stack in reverse order to get the topological sort.
Lastly, we create a Graph object and call add_edge to add edges to the graph, and then call topological_sort to get the topological sort.
The final output of the topological_sort method is a list of sorted nodes in the topological order. In this implementation, the output would be ['A', 'B', 'C', 'D'].
We add a grid, and labels for the x-axis, y-axis, and title. Finally, we call plt.show() to display the chart.
The final output of the program is a bubble chart with random values for x-axis, y-axis, and bubble sizes.
In this implementation, we define two classes: Bubble and BubbleChart. The Bubble class represents a single bubble in the chart, and has attributes for the x-axis value (x), y-axis value (y), size (z), label, and color. The BubbleChart class represents the entire chart, and is used to store, add, and remove the Bubble objects.
The BubbleChart class has a constructor that initializes an empty list to hold the bubbles. It has methods to add (add_bubble) and remove (remove_bubble) bubbles from the list, as well as get the list of bubbles (get_bubbles), and to clear the list of all bubbles (clear).
In addition to these methods, the BubbleChart class also has methods to get the x-values (get_x_values), the y-values (get_y_values), and the size-values (get_z_values) from the list of bubbles. These methods return a list of values that can be used to plot the chart.
This data structure can be used to store the data for a bubble chart, allows data to be added, removed, cleared, and accessed, and provides helpful methods to get the x, y, and size values for plotting the chart.