python
python
arr = [8, 6, 9]
radix(arr)
print(arr)
Count: Knapsack:
n = int(input("Enter the element number:")) def knapsack_01(table, value, weight, i, wt):
arr = [] if i == 0 or wt == 0:
for i in range(n): return 0
num = int(input()) if table[i][wt] != -1:
arr.append(num) return table[i][wt]
largest_number = max(arr)
count = [0] * (largest_number+1) if weight[i] > wt:
for element in arr: return knapsack_01(table, value, weight, i - 1,
count[element] += 1 wt)
for i in range(1, len(count)): else:
count[i] += count[i - 1] take = value[i] + knapsack_01(table, value,
output = [0] * len(arr) weight, i - 1, wt - weight[i])
for item in reversed(arr): leave = knapsack_01(table, value, weight, i - 1,
output[count[item] -1] = item wt)
count[item] -= -1 table[i][wt] = max(take, leave)
print("sorted array", output)
return table[i][wt]
Knapsackk2: n = int(input("Enter the number of items: "))
n = int(input("How many items? ")) value = input("Enter the values of the %d item(s) in
value = [None] * (n+1) order: " % n).split(' ')
weight = [None] * (n+1) value = [int(i) for i in value]
print("Enter imtems' value in separate lines.") value.insert(0, None) # ith item's value at i index
for i in range(1, n+1):
weight = input("Enter the weight of the %d item(s) in
value[i], weight[i] = map(int, input("Item %d: "
order: " % n).split(' ')
%i).split(' '))
capacity = int(input("Capacity: ")) weight = [int(i) for i in weight]
table = [[None for i in range(capacity+1)] for j in weight.insert(0, None) # ith item's weight at i index
range(n+1)] W = int(input("Enter total capacity: "))
for i in range(n+1): table = [[-1 for i in range(W + 1)] for i in range(n + 1)]
for w in range(capacity+1): print("Maximum profit: ", knapsack_01(table, value,
if i == 0 or w == 0: weight, n, W))
table[i][w] = 0
elif weight[i] > w: Coin:
table[i][w] = table[i-1][w] from math import inf
else:
target = int(input("S = "))
table[i][w] = max(table[i-1][w], value[i]+table[i-
coins = list(map(int, input("Enter coins value:
1][w-weight[i]])
").split()))
print(table[n][capacity]) table = [inf] * (target + 1)
print("Selected items: ") table[0] = 0
i=n for s in range(1, target + 1):
w = capacity for c in coins:
while i > 0 and w > 0: if c <= s:
if table[i][w] != table[i-1][w]: count = table[s - c] + 1
print(i, end=' ') if count < table[s]:
w = w - weight[i] table[s] = count
i=i-1
if table[target] == inf:
else:
print("No solution possible")
i = i-1
else:
print(f"Number of coins: {table[target]}")
Coin2: Topologicalsort:
from math import inf # DFS with cycle detection and topological sort
def dfs(u):
global cycle_found
target = int(input("S = "))
color[u] = "gray"
for v in adj[u]:
coins = list(map(int, input("Enter coins value: ").split())) if color[v] == "white":
dfs(v)
elif color[v] == "gray":
table = [inf] * (target + 1) cycle_found = True
table[0] = 0 color[u] = "black"
list_coins = [-1] * (target + 1) topo_order.append(u)
if cycle_found:
print("Cycle detected. Topological sort not
possible.")
else:
print("Topological Order:", "
".join(reversed(topo_order)))
BFS with numpy: Without numpy:
from collections import defaultdict import queue
from queue import Queue
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2) Dijaskstra:
g.add_edge(2, 3, 3) from queue import PriorityQueue
g.add_edge(2, 5, 2) import math
g.add_edge(2, 4, 4) class Node:
g.add_edge(3, 2, 3) def __init__(self, name):
g.add_edge(3, 4, 3) self.name = name
g.add_edge(4, 2, 4) self.key = math.inf # Distance from source
g.add_edge(4, 3, 3) self.parent = None
g.add_edge(5, 2, 2) self.visited = False
g.add_edge(5, 4, 3) self.adj = [] # List of tuples: (neighbor_node,
weight)
print("Edges in the Minimum Spanning Tree:") def __lt__(self, other): # Needed for
g.kruskal_algo() PriorityQueue
return self.key < other.key
Strongly: def dijkstra(start_node):
from collections import defaultdict start_node.key = 0
q = PriorityQueue()
class Graph: q.put(start_node)
while not q.empty():
def __init__(self, vertex): # Fixed __init__ method u = q.get()
self.V = vertex if u.visited:
self.graph = defaultdict(list) continue
u.visited = True
# Add edge into the graph for v, weight in u.adj:
def add_edge(self, s, d): if not v.visited and u.key + weight < v.key:
self.graph[s].append(d) v.key = u.key + weight
v.parent = u
# DFS q.put(v)
def dfs(self, d, visited_vertex): def get_path(destination):
visited_vertex[d] = True path = []
print(d, end=' ') current = destination
for i in self.graph[d]: while current:
if not visited_vertex[i]: path.append(current.name)
self.dfs(i, visited_vertex) current = current.parent
return path[::-1]
def fill_order(self, d, visited_vertex, stack):
visited_vertex[d] = True # ---------------- Input Section ---------------- #
for i in self.graph[d]:
if not visited_vertex[i]: # Input node names
self.fill_order(i, visited_vertex, stack) node_input = input("Enter nodes name: ").split()
stack.append(d) # Fixed append usage Nodes = {name: Node(name) for name in
node_input}
# Transpose the graph
def transpose(self): # Input number of edges
g = Graph(self.V) num_edges = int(input("NO of edges: "))
for i in self.graph: print("Edge info: (u,v,w)")
for j in self.graph[i]: for i in range(num_edges):
g.add_edge(j, i) edge_input = input(f"Edge {i+1}: ").split()
return g u, v, w = edge_input[0], edge_input[1],
int(edge_input[2])
# Print strongly connected components Nodes[u].adj.append((Nodes[v], w))
def print_scc(self): Nodes[v].adj.append((Nodes[u], w)) # Assuming
stack = [] undirected graph
visited_vertex = [False] * self.V
# Input source and destination
for i in range(self.V): source_name = input("Source node: ")
if not visited_vertex[i]: destination_name = input("Destination node: ")
self.fill_order(i, visited_vertex, stack)
# ---------------- Run Dijkstra ---------------- #
gr = self.transpose() dijkstra(Nodes[source_name])
visited_vertex = [False] * self.V
# ---------------- Output Section ---------------- #
while stack: path = get_path(Nodes[destination_name])
i = stack.pop() cost = Nodes[destination_name].key
if not visited_vertex[i]:
gr.dfs(i, visited_vertex) print(f"\noutput:")
print("") print(f"cost: {cost}")
print("path:", ' '.join(path))