Skip to content

Commit 13802fc

Browse files
DanishSheikh1999cclauss
authored andcommitted
Create greedy.py (TheAlgorithms#1359)
* Create greedy.py * Update greedy.py * Add a doctest and format with black * Update build_directory_md.py
1 parent 5483064 commit 13802fc

File tree

2 files changed

+65
-4
lines changed

2 files changed

+65
-4
lines changed

other/greedy.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class things:
2+
def __init__(self, n, v, w):
3+
self.name = n
4+
self.value = v
5+
self.weight = w
6+
7+
def __repr__(self):
8+
return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})"
9+
10+
def get_value(self):
11+
return self.value
12+
13+
def get_name(self):
14+
return self.name
15+
16+
def get_weight(self):
17+
return self.weight
18+
19+
def value_Weight(self):
20+
return self.value / self.weight
21+
22+
23+
def build_menu(name, value, weight):
24+
menu = []
25+
for i in range(len(value)):
26+
menu.append(things(name[i], value[i], weight[i]))
27+
return menu
28+
29+
30+
def greedy(item, maxCost, keyFunc):
31+
itemsCopy = sorted(item, key=keyFunc, reverse=True)
32+
result = []
33+
totalValue, total_cost = 0.0, 0.0
34+
for i in range(len(itemsCopy)):
35+
if (total_cost + itemsCopy[i].get_weight()) <= maxCost:
36+
result.append(itemsCopy[i])
37+
total_cost += itemsCopy[i].get_weight()
38+
totalValue += itemsCopy[i].get_value()
39+
return (result, totalValue)
40+
41+
42+
def test_greedy():
43+
"""
44+
>>> food = ["Burger", "Pizza", "Coca Cola", "Rice",
45+
... "Sambhar", "Chicken", "Fries", "Milk"]
46+
>>> value = [80, 100, 60, 70, 50, 110, 90, 60]
47+
>>> weight = [40, 60, 40, 70, 100, 85, 55, 70]
48+
>>> foods = build_menu(food, value, weight)
49+
>>> foods # doctest: +NORMALIZE_WHITESPACE
50+
[things(Burger, 80, 40), things(Pizza, 100, 60), things(Coca Cola, 60, 40),
51+
things(Rice, 70, 70), things(Sambhar, 50, 100), things(Chicken, 110, 85),
52+
things(Fries, 90, 55), things(Milk, 60, 70)]
53+
>>> greedy(foods, 500, things.get_value) # doctest: +NORMALIZE_WHITESPACE
54+
([things(Chicken, 110, 85), things(Pizza, 100, 60), things(Fries, 90, 55),
55+
things(Burger, 80, 40), things(Rice, 70, 70), things(Coca Cola, 60, 40),
56+
things(Milk, 60, 70)], 570.0)
57+
"""
58+
59+
60+
if __name__ == "__main__":
61+
import doctest
62+
63+
doctest.testmod()

scripts/build_directory_md.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def print_path(old_path: str, new_path: str) -> str:
2525
for i, new_part in enumerate(new_path.split(os.sep)):
2626
if i + 1 > len(old_parts) or old_parts[i] != new_part:
2727
if new_part:
28-
print(f"{md_prefix(i-1)} {new_part.replace('_', ' ').title()}")
28+
print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
2929
return new_path
3030

3131

@@ -36,9 +36,7 @@ def print_directory_md(top_dir: str = ".") -> None:
3636
if filepath != old_path:
3737
old_path = print_path(old_path, filepath)
3838
indent = (filepath.count(os.sep) + 1) if filepath else 0
39-
url = "/".join((URL_BASE, filepath.split(os.sep)[1], filename)).replace(
40-
" ", "%20"
41-
)
39+
url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20")
4240
filename = os.path.splitext(filename.replace("_", " "))[0]
4341
print(f"{md_prefix(indent)} [{filename}]({url})")
4442

0 commit comments

Comments
 (0)