cheetsheet python
cheetsheet 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-1]
coins = list(map(int, input("Enter coins value:
[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:
Coin2: print(f"Number of coins: {table[target]}")
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]:
if color[v] == "white":
coins = list(map(int, input("Enter coins value: ").split()))
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)
table[s] = table[s-c] + 1
for node in nodes:
list_coins[s] = c color[node] = "white"
adj[node] = []
if table[target] == inf:
print("No solution possible") for i in range(e):
else: u, v = input(f"Edge {i+1} (u -> v): ").split()
print(f"Number of coins: {table[target]}") adj[u].append(v) # Directed edge only
if cycle_found:
print("Cycle detected. Topological sort not
possible.")
else:
print("Topological Order:", "
".join(reversed(topo_order)))
Without numpy:
BFS with numpy: import queue
from collections import defaultdict
from queue import Queue
def bfs(adj, source):
n = int(input("Please enter the number of nodes: ")) visited = [0 for i in range(len(adj))]
e = int(input("Please enter the number of edges: "))
q = queue.Queue(maxsize=len(adj))
# creating adjacency list using dictionary
adj = defaultdict(list) q.put(source)
for i in range(e): visited[source] = 1
u, v = input("Edge %d: " % (i + 1)).split()
adj[u].append(v) while not q.empty():
adj[v].append(u) current_node = q.get()
print(current_node, end=' ')
# Performing BFS
q = Queue(maxsize=len(adj)) for i in range(len(adj[current_node])): # not
visited = set() a pythonic way
s = input("Enter the source node: ") adjacent_node = adj[current_node][i]
q.put(s) if visited[adjacent_node] == 0:
visited.add(s) visited[adjacent_node] = 1
q.put(adjacent_node)
print("BFS: ", end='')
while not q.empty():
u = q.get() n = int(input("Enter the number of nodes: "))
print(u, end=' ') e = int(input("Enter the number of edges: "))
Withoutnumpy dfs:
DFS: def dfs(adj, visited, current_node):
def dfs(u): if visited[current_node] != 0:
color[u] = 'gray' return
visited[current_node] = 1
for element in adj[u]: for i in range(len(adj[current_node])): # not a
if color[element] == 'white': pythonic way
dfs(element) adjacent_node = adj[current_node][i]
if visited[adjacent_node] == 0:
dfs(adj, visited, adjacent_node)
color[u] = 'black' print(current_node, end=' ')
print(u, end=' ') # for neighbour in adj[current_node]: #
pythonic way
# if visited[neighbour] == 0: # if neighbour
# as we want to allow any vertex name not only 0 to not in visited:
n-1 # dfs(adj, visited, neighbour)
# we need have complete list of all vertices name
nodes = input("Enter nodes' name: ").split() n = int(input("Enter the number of nodes: "))
e = int(input("Number of edges: ")) e = int(input("Enter the number of edges: "))
# creating dictionary to store adjacency list of each adj_list = [[] for i in range(n)]
vertex
adj = {} print("Enter edges in separate lines.")
# creating a dictionary to store color's value of each for i in range(e):
vertex u, v = map(int, input().split())
color = {} adj_list[u].append(v)
# adding all vertex name as key and an empty list as adj_list[v].append(u)
corresponding value
# adding white color to each vertex
for element in nodes: print(adj_list)
adj[element] = []
color[element] = 'white' visited = [0 for i in range(n)]
print('DFS: ', end="")
# creating adjacency list for i in range(n):
for i in range(e): if visited[i] == 0:
u, v = input("Edge %d: " % (i + 1)).split() dfs(adj_list, visited, i)
adj[u].append(v) """
# if graph is directed then we must eliminate the Sample input / output
following line Enter the number of nodes: 5
adj[v].append(u) Enter the number of edges: 4
graph 08 dfs with name.py Enter edges in separate lines.
Displaying graph 07 dfs without name.py. 02
21
23
04
DFS: 1 3 2 4 0
"""
graph 07 dfs without name.py
Displaying graph 07 dfs without name.py.
Prims:
Kruskals: # Prim's Algorithm in Python
class Graph:
def __init__(self, vertices): # Fixed constructor
self.V = vertices INF = 9999999
self.graph = []
def add_edge(self, u, v, w): V=5
self.graph.append([u, v, w])
def find(self, parent, i): G = [[0, 9, 75, 0, 0],
if parent[i] == i: [9, 0, 95, 19, 42],
return i [75, 95, 0, 51, 66],
return self.find(parent, parent[i]) [0, 19, 51, 0, 31],
def apply_union(self, parent, rank, x, y): [0, 42, 66, 31, 0]]
xroot = self.find(parent, x)
yroot = self.find(parent, y) selected = [0, 0, 0, 0, 0]
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot no_edge = 0
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot selected[0] = True
else:
parent[yroot] = xroot print("Edge : Weight\n")
rank[xroot] += 1 while (no_edge < V - 1):
def kruskal_algo(self):
result = [] minimum = INF
i, e = 0, 0 x=0
self.graph = sorted(self.graph, key=lambda item: y=0
item[2]) for i in range(V):
parent = [] if selected[i]:
rank = [] for j in range(V):
for node in range(self.V): if ((not selected[j]) and G[i][j]):
parent.append(node)
rank.append(0) if minimum > G[i][j]:
while e < self.V - 1: minimum = G[i][j]
u, v, w = self.graph[i] x=i
i=i+1 y=j
x = self.find(parent, u) print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
y = self.find(parent, v) selected[y] = True
if x != y: no_edge += 1
e=e+1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print("%d - %d: %d" % (u, v, weight))
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) Dijaskstra:
g.add_edge(2, 1, 2) from queue import PriorityQueue
g.add_edge(2, 3, 3) import math
g.add_edge(2, 5, 2) class Node:
g.add_edge(2, 4, 4) def __init__(self, name):
g.add_edge(3, 2, 3) self.name = name
g.add_edge(3, 4, 3) self.key = math.inf # Distance from source
g.add_edge(4, 2, 4) self.parent = None
g.add_edge(4, 3, 3) self.visited = False
g.add_edge(5, 2, 2) self.adj = [] # List of tuples: (neighbor_node,
g.add_edge(5, 4, 3) weight)
def __lt__(self, other): # Needed for
print("Edges in the Minimum Spanning Tree:") PriorityQueue
g.kruskal_algo() return self.key < other.key
def dijkstra(start_node):
Strongly: start_node.key = 0
from collections import defaultdict q = PriorityQueue()
q.put(start_node)
class Graph: while not q.empty():
u = q.get()
def __init__(self, vertex): # Fixed __init__ method if u.visited:
self.V = vertex continue
self.graph = defaultdict(list) u.visited = True
for v, weight in u.adj:
# Add edge into the graph if not v.visited and u.key + weight < v.key:
def add_edge(self, s, d): v.key = u.key + weight
self.graph[s].append(d) v.parent = u
q.put(v)
# DFS def get_path(destination):
def dfs(self, d, visited_vertex): path = []
visited_vertex[d] = True current = destination
print(d, end=' ') while current:
for i in self.graph[d]: path.append(current.name)
if not visited_vertex[i]: current = current.parent
self.dfs(i, visited_vertex) return path[::-1]