From 4e6159720c2f1024470ad6ed095110da87c01b2a Mon Sep 17 00:00:00 2001 From: ahmedabougabal Date: Tue, 21 Jan 2025 22:54:39 +0200 Subject: [PATCH] feat(algo): implements an optimized readable breadth first search approach as the most dynnamic/flexible/memory effecient O(n) solution to process the dictionary level by level till finds gets 'color' from value of the item_name --- whatTasteIsItLike.py | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/whatTasteIsItLike.py b/whatTasteIsItLike.py index 3cefdb4..3890449 100644 --- a/whatTasteIsItLike.py +++ b/whatTasteIsItLike.py @@ -1,10 +1,38 @@ +# def describe_items(food_items, color): +# # Write your code here. +# apple_taste = food_items['fruits']['temperate']['apple']['taste'] +# beet_taste = food_items['vegetables']['root']['beet']['taste'] +# return [f"The apple is {apple_taste}.", f"The beet is {beet_taste}."] + +from collections import deque +# iterative approach (most-effiecient O(N)- Breadth first Search) def describe_items(food_items, color): - # Write your code here. - apple_taste = food_items['fruits']['temperate']['apple']['taste'] - beet_taste = food_items['vegetables']['root']['beet']['taste'] - return [f"The apple is {apple_taste}.", f"The beet is {beet_taste}."] - + result = [] + queue = deque(food_items.items()) + + while queue: + item_name , val = queue.popleft() + # print("\nCurrent Queue Contents:") for debugging + # for item in queue: + # print(item) + if isinstance(val, dict): # check if the current value is a dict + # then we have 2 possibilites + if val.get('color') == color: + result.append(f"The {item_name} is {val['taste']}.") + else: # Add child items to the queue for further processing + queue.extend(val.items()) # we add unprocessed items to the right using extend and we pop from the left "BFS Under the hood to completely process the dict as a tree of nodes" + + return result + + + +""" +levels traversed in BFS : TIME COMPLEXITY IS O(N) +Level 1: 2 nodes (fruits, vegetables) +Level 2: 4 nodes (tropical, temperate, leafy, root) +Level 3: 8 nodes (mango, pineapple, apple, pear, spinach, kale, carrot, beet) +""" # This is how your code will be called. @@ -65,3 +93,5 @@ def describe_items(food_items, color): } } #* ['The apple is sweet.', 'The beet is earthy.'] is the expected output. +# print(food_items.items()) +print(describe_items(food_items, 'red')) \ No newline at end of file