generated from Code-Institute-Org/p3-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplanner.py
321 lines (280 loc) · 12 KB
/
planner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# This module provides objects and methods for planning dinner parties
# STANDARD PACKAGES
# import sleep to show output for some time period
# package suggested by my mentor
from time import sleep
# 3RD PARTY LIBRARIES
# get combinations from a list
import itertools
# colored terminal output
# package suggested by my mentor
from colorama import Fore, Back
# SELF-WRITTEN MODULES & FUNCTIONS
# general-purpose functions
from utilities import validate_range, clear
class DishList:
"""
Create an instance of DishList: a list of strings
"""
def __init__(self, dish_data):
self.dish_data = dish_data
def print_enum(self):
"""
Print available dishes in a numbered list
"""
# sort list alphabetically
self.dish_data.sort()
# print an empty line to visually separate the list
print('\n')
# for each item starting from 1 (not 0), print its index (in green)
# and the item
for i in range(1, len(self.dish_data)):
print(Fore.GREEN + str(i) + Fore.RESET, self.dish_data[i])
# print an empty line to visually separate the list
print('\n')
def select_dish(self):
"""
Select a dish based on user input
"""
# print the list of dishes in a numbered list
self.print_enum()
# validating the input
text = [f'{Back.MAGENTA}Type in the '
f'{Fore.GREEN}number{Fore.RESET} '
"of the dish you'd like to add:"
f'{Back.RESET} ']
dish_number = \
validate_range(text, int, 1, len(self.dish_data) - 1)
# get the dish with the selected number from the `dishes` list
selected_dish = self.dish_data[int(dish_number)]
# print the selected dish's name
print(f'\nYou have selected: {selected_dish}')
# sleep for 1.5 seconds after printing output
sleep(0.5)
# clear the console
clear()
# remove the selected dish from the list of available dishes
self.dish_data.remove(selected_dish)
return selected_dish
def parse_string(ingredient_string):
"""
Find the abbreviation string,
replace it with the full unit name
if it is in the dictionary
:param string ingredient_string: must contain ( and )
:returns list: [opening parenthesis index,
abbreviation,
Boolean: abbr in dictionary or not,
string: modified intput string]
"""
# abbreviations and corresponding unit names
units = {
'g': 'grams',
'kg': 'kilograms',
'pc': 'pieces',
'ml': 'milliliters',
'l': 'liters',
'Tbsp': 'tablespoons',
'cloves': 'cloves',
}
# find the index of the opening bracket in the string
opening = ingredient_string.index('(')
# replace measurement unit abbreviation with full name
# get the substring between the opening and the closing bracket
abbr = ingredient_string[opening:].partition(')')
# get the first item (opening bracket plus abbreviation)
abbr = abbr[0]
# delete the opening bracket from the variable
abbr = abbr.replace('(', '')
# if the abbreviation is in the `units` dictionary,
# replace it with the corresponding unit name
if abbr in units:
unit_name = units[abbr]
in_dict = True
# if it's not in the dictionary, leave it as is
else:
unit_name = abbr
in_dict = False
# replace a parenthesis+abbreviation with parenthesis+unit name
# need to specify parenthesis as well, so that it does not
# replace things like "g" across the board (unintended)
ingredient_string = ingredient_string.replace('(' + abbr, '(' + unit_name)
return [opening, unit_name, in_dict, ingredient_string]
def print_formatted(ingredient_list):
""" Print ingredient list in a user-friendly string format
:ingredient_list: a list where each item is a list containing a string
and a number. The string must contain ( and )
:type ingredient_list list
"""
# print an empty line to visually separate the block
print('\n')
# for every item in the list
for i in range(0, len(ingredient_list)):
# set `print_string` as the first item of the list
print_string = ingredient_list[i][0]
quantity = ingredient_list[i][1]
# replace unit abbreviation with full name
parsed_string = parse_string(print_string)
# get the index of the opening parenthesis
opening = parsed_string[0]
# get the unit name
unit_name = parsed_string[1]
# get whether the unit name is in the dictionary
in_dict = parsed_string[2]
# get the print string
print_string = parsed_string[3]
# if the quantity is exactly 1, and unit is in the dictionary
if quantity == 1 and in_dict:
# replace unit_name with singular version (remove string-final 's')
print_string = print_string.replace(unit_name, unit_name[:-1])
# end of code to replace measurement abbreviation with full name
# 1 place left of the opening parenthesis, add the following:
# a colon
# the quantity (second item of the list) in general notation
# re-add the rest of the string
print_string = print_string[:opening - 1] \
+ ': ' \
+ f'{quantity:g}' \
+ print_string[opening - 1:]
# delete the opening and closing parenthesis
print_string = print_string.replace('(', '')
print_string = print_string.replace(')', '')
# print the string in green
print(Fore.GREEN + print_string + Fore.RESET)
class ShoppingList:
"""
Create an instance of ShoppingList
"""
def __init__(self, list_data):
"""
:param list list_data: [ingredient (unit), quantity]
"""
self.list_data = list_data
def get_ingredients(self, selection, recipe_data):
"""Get list of ingredients for a selected dish, print them out,
add them to the shopping list, return a list of lists
:param string selection: the name of the selected dish
:type recipe_data: list
:param recipe_data: the database containing the dishes, ingredients
and quantities
:returns: list
"""
print(Fore.GREEN + f'\nIngredients for {selection}' + Fore.RESET)
# get the index of the selected dish in the database
selection_index = recipe_data[1].index(selection)
# the list of ingredients for the selected dish
dish_ingredients = []
# go through each row
for row in recipe_data:
# if the cell in the row under the selected dish has content
# (ingredient quantity)
# and it's not one of the first 2 rows
if row[selection_index] and recipe_data.index(row) > 1:
# add the list [ingredient, quantity(converted to a float)]
# to the shopping list
dish_ingredients.append([row[0], float(row[selection_index])])
# sort list alphabetically
dish_ingredients.sort()
# print the ingredients for the selected dish
print_formatted(dish_ingredients)
# add each ingredient from the selected dish to the shopping list
for ingredient in dish_ingredients:
self.list_data.append(ingredient)
# sort list alphabetically
self.list_data.sort()
return self.list_data
def unify_ingredients(self, selection, recipe_data):
"""Check shopping list for pairs of items (lists)
where the ingredient is the same.
Add quantities of the ingredient together.
Return modified shopping list.
:type selection
:param selection: the name of the selected dish
:type recipe_data: list
:param recipe_data: the database containing the dishes, ingredients and
quantities
:returns: list
"""
# this needs to be run every time items are added to the shopping list
self.list_data = self.get_ingredients(selection, recipe_data)
# get all pairs of items within the shopping list item
for x, y in itertools.combinations(self.list_data, 2):
# if the ingredient name and unit (first item of both lists)
# is the same
if x[0] == y[0]:
# TESTING: print for testing/development
# print pairs of items where the ingredient is the same
# print(x, y)
# add a new item (list)
# with this ingredient name and unit as its first item,
# and the sum of the two quantities as the second item
self.list_data.append([x[0], x[1] + y[1]])
# remove the two original items from shopping list
self.list_data.remove(x)
self.list_data.remove(y)
print('\nShopping list updated ✅\n')
# ask_more()
return self.list_data
def check_pantry(self):
"""
For each item on the shopping list, ask the user how much they have.
Subtract answer from quantity. If quantity becomes zero or less,
remove item from the list.
"""
# confirm starting pantry check
print("\nLet's check your pantry, then! 👍\n")
# sleep for 1.5 seconds after printing output
sleep(1.5)
clear()
# create an intermediate list to store ingredients where quantity
# is more than 0
# this is needed because removing items from a list in a loop causes
# "index out of range" issues
# list comprehension also doesn't work well with list of lists
revised_list = []
# for each item on the shopping list
for i in range(0, len(self.list_data)):
# parse ingredient text, replace measurement abbreviation
# with full unit name
parsed_text = parse_string(self.list_data[i][0])
# the index of the opening parenthesis
opening = parsed_text[0]
# the full name of the measurement unit
unit_name = parsed_text[1]
# Boolean: whether the unit name is in the dictionary
in_dict = parsed_text[2]
# the ingredient string ("ingredient (measurement)")
ingredient_text = parsed_text[3]
# delete string content starting from the space
# before the opening parenthesis
ingredient_text = ingredient_text[:opening - 1]
# ask how much of the given ingredient the user has
text = [f'How many {Fore.MAGENTA}{unit_name}{Fore.RESET} '
f'of {Fore.GREEN}{ingredient_text}{Fore.RESET} '
f'do you have?\n'
f'{Back.MAGENTA}Type {Fore.GREEN}0{Fore.RESET} '
f'if you don\'t have any{Back.RESET}: ']
# get and validate the input (float, >=0, no upper limit)
have = validate_range(text, float, 0)
# if the quantity is exactly 1, and the unit is in the dictionary
if have == 1 and in_dict:
# make unit_name singular (remove string-final 's')
unit_name = unit_name[:-1]
# print confirmation with user input
print(
f'Got it, you have {have:g} {unit_name} of {ingredient_text}\n'
)
# sleep for 1.5 seconds after printing output
sleep(1.5)
# deduct the quantity in the pantry
# from the quantity on the shopping list
self.list_data[i][1] -= have
# if the resulting quantity is more than 0
if self.list_data[i][1] > 0:
# add the whole item to the new intermediate list
revised_list.append(self.list_data[i])
# set the contents of the shopping list to the intermediate list
self.list_data = revised_list
print('\nAll done checking your pantry! 🎉\n')
# sleep for 1.5 seconds after printing output
sleep(1.5)