Skip to content

Commit b89ac27

Browse files
authored
Merge pull request AllAlgorithms#23 from beingadityak/greedy_algos
3 Greedy Algorithms in Python
2 parents 514f801 + 0bd27e8 commit b89ac27

File tree

3 files changed

+135
-0
lines changed

3 files changed

+135
-0
lines changed

greedy/coin_change.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Coin Change implementation in Python (Greedy Method)
5+
"""
6+
7+
__author__ = "Aditya Krishnakumar"
8+
9+
def minimum_coins(value, denominations):
10+
result = []
11+
# Assuming denominations is sorted in descendig order
12+
for cur_denom in denominations:
13+
while cur_denom <= value:
14+
result.append(cur_denom)
15+
value = value - cur_denom
16+
17+
return result
18+
19+
# Testing
20+
def test():
21+
scenarios = [[100, [50, 25, 10, 5, 1], [50, 50]],
22+
[101, [50, 25, 10, 5, 1], [50, 50, 1]],
23+
[77, [50, 25, 10, 5, 1], [50, 25, 1, 1]],
24+
[38, [50, 25, 10, 5, 1], [25, 10, 1, 1, 1]],
25+
[17, [50, 25, 10, 5, 1], [10, 5, 1, 1]],
26+
[3, [50, 25, 10, 5, 1], [1, 1, 1]],
27+
[191, [100, 50, 25, 10, 5, 1], [100, 50, 25, 10, 5, 1]]]
28+
29+
for scenario in scenarios:
30+
actual = minimum_coins(scenario[0], scenario[1])
31+
if actual != scenario[2]:
32+
message = "Test Failed: Value: {}, Denominations: {}, Expected Result: {}, Actual Result: {}".format(scenario[0], scenario[1], scenario[2], actual)
33+
print message
34+
35+
return None
36+
37+
test()

greedy/dijkstra_algo.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Dijkstra's Algorithm implementation in Python
5+
"""
6+
7+
__author__ = "Aditya Krishnakumar"
8+
9+
def dijkstra(graph, source):
10+
11+
vertices, edges = graph
12+
dist = dict()
13+
previous = dict()
14+
15+
for vertex in vertices:
16+
dist[vertex] = float("inf")
17+
previous[vertex] = None
18+
19+
dist[source] = 0
20+
Q = set(vertices)
21+
22+
while len(Q) > 0:
23+
u = minimum_distance(dist, Q)
24+
print('Currently considering', u, 'with a distance of', dist[u])
25+
Q.remove(u)
26+
27+
if dist[u] == float('inf'):
28+
break
29+
30+
n = get_neighbours(graph, u)
31+
for vertex in n:
32+
alt = dist[u] + dist_between(graph, u, vertex)
33+
if alt < dist[vertex]:
34+
dist[vertex] = alt
35+
previous[vertex] = u
36+
37+
return previous

greedy/fractional_knapsack.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
Implementation of Fractional Knapsack Algorithm in Python
5+
"""
6+
7+
__author__ = "Aditya Krishnakumar"
8+
9+
# Item class with weight and values
10+
class Item:
11+
12+
# intialize weight and values
13+
def __init__(self, weight=0, value=0):
14+
15+
self.weight = weight
16+
self.value = value
17+
18+
return
19+
20+
21+
def fractional_knapsack(items, W):
22+
23+
# Sorting items by value /weight
24+
sorted(items, key = lambda item: float(item.value)/float(item.weight))
25+
26+
finalValue = 0.0
27+
currentWeight = 0
28+
29+
30+
for item in items:
31+
32+
if currentWeight + item.weight <= W :
33+
# If adding Item won't overflow, add it completely
34+
finalValue += item.value
35+
currentWeight += item.weight
36+
37+
else:
38+
#If we can't add current Item, add a fraction of it
39+
remaining = W - currentWeight
40+
finalValue += item.value*(float(remaining)/float(item.weight))
41+
break
42+
43+
return finalValue
44+
45+
def main():
46+
47+
W = 50
48+
49+
items = [
50+
Item(10, 60),
51+
Item(20, 100),
52+
Item(30, 120)
53+
]
54+
55+
print("Maximum value we can obtain -{}".format(fractional_knapsack(items, W)))
56+
57+
return
58+
59+
if __name__ == "__main__":
60+
61+
main()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy