I've been stuck for hours please help me find a way to compare the keys in the queue to dictionary and finding the minimum value.
Below is the code I have so far. I try using min() but it doesnt work.
def find_min(label,queue):
for i in queue:
for l in label:
for s in label[i]:
list1 = []
return min(l[1])
bellow is the label and queue input
You can use the following.
Code
def find_min(labels, queue):
# Sort labels dictionary based upon last item in values list
# which will be a number (kv[1] is value list, kv[1][-1] is last value in list)
sorted_labels = dict(sorted(labels.items(), key = lambda kv: kv[1][-1]))
# Get the keys in order from sorted_labels that are also in the queue
options = [k for k in sorted_labels if k in queue]
# Return the first one (will be the smallest)
return options[0] if options else None
Test
print(find_min({"A" : [0], "B" : ["A",10], "C" : ["B",10], "D" : ["C",15]}, ["A", "D"]))
# Output: A
print(find_min({"A" : [0], "B" : ["A",10], "C" : ["B",10], "D" : ["C",15]}, ["B", "C", "D"]))
# Output: B
Simpler Alternative
def find_min(labels, queue):
# Initialize min value
k_min, v_min = None, None
for k, v in labels.items():
if k in queue:
# Only check keys in queue
if v_min is None or v[-1] < v_min:
# Don't have a min yet, or less than current min
v_min = v[-1]
k_min = k
return k_min
Test
print(find_min({"A" : [0], "B" : ["A",10], "C" : ["B",10], "D" : ["C",15]}, ["A", "D"]))
# Output: A
print(find_min({"A" : [0], "B" : ["A",10], "C" : ["B",10], "D" : ["C",15]}, ["B", "C", "D"]))
# Output: B
Using Poster's Code
def find_min(label,queue):
kmin = None
value_min = None
for l in label:
if l in queue:
value = label[l]
n = len(value)
last_value = value[n-1]
if kmin is None or last_value < value_min:
kmin = l
value_min = last_value
return kmin