Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions python/Bellman-FordAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
def bellman_ford(vertex_count, edges, source):
dist = [float('inf')] * vertex_count
pred = [None] * vertex_count
dist[source] = 0
for _ in range(vertex_count - 1):
updated = False
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
updated = True
if not updated:
break
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
return None, None
return dist, pred

def reconstruct_path(pred, target):
path = []
while target is not None:
path.append(target)
target = pred[target]
return path[::-1]

if __name__ == "__main__":
vertex_count = 5
edges = [
(0, 1, 6),
(0, 2, 7),
(1, 2, 8),
(1, 3, 5),
(1, 4, -4),
(2, 3, -3),
(2, 4, 9),
(3, 1, -2),
(4, 3, 7)
]
source = 0
dist, pred = bellman_ford(vertex_count, edges, source)
if dist is None:
print("Graph contains a negative-weight cycle")
else:
for v in range(vertex_count):
if dist[v] == float('inf'):
print(f"Vertex {v}: unreachable")
else:
path = reconstruct_path(pred, v)
print(f"Vertex {v}: distance = {dist[v]}, path = {path}")
25 changes: 25 additions & 0 deletions python/knapsak.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
def fractional_knapsack(values, weights, max_capacity):
n = len(values)
items = [[values[i], weights[i]] for i in range(n)]
items.sort(key=lambda x: x[0] / x[1], reverse=True)

total_value = 0.0
remaining_capacity = max_capacity

for value, weight in items:
if weight <= remaining_capacity:
total_value += value
remaining_capacity -= weight
else:
total_value += (value / weight) * remaining_capacity
break

return total_value


if __name__ == "__main__":
values = [60, 100, 120]
weights = [10, 20, 30]
max_capacity = 50

print(fractional_knapsack(values, weights, max_capacity))