Reputation: 27
First of all sorry for the confusing title, I had no idead how to explain my problem without an example.
I have the following graph
graph = {
1: [(3, 5), (4, 1), (5, 4)],
2: [(5, 9)],
3: [(5, 1), (6, 1)],
4: [(2, 11), (8, 2)],
5: [(4, 6), (2, 6)],
6: [(7, 1)],
7: [(5, 7), (2, 1)],
8: [(2, 6)],
}
I want to be able to get the smallest number from the second item of the tupels for a given number. For example, if I gave the function the number 1 I would want it to return the 1 from the second tupel. If the input was 4 instead I would expect it to return a 2 form the second tupel.
My current approach is min((graph[s])[1])
, but this doesn't really work and mostly returns Index Errors.
Edit:
I solved the problem with (min(graph[s])[0], min(graph[s])[1])[1]
now (for some reason) it works in all cases (the problems were with lists that only contained one tupel).
Upvotes: 0
Views: 148
Reputation: 111
min((graph[key])[1])
works for me.
You can try : min([x[1] for x in graph[key]])
Upvotes: 0
Reputation: 9504
Try this:
def get_smallest_num(key):
return min(map(lambda x: x[1], graph[key]))
print(get_smallest_num(1)) # 1
print(get_smallest_num(5)) # 6
Upvotes: 0
Reputation: 54168
Your problem comes when dealing when pair like 2: [(5, 9)]
where there is juse 1 item, when accessing [1]
this will fail, you gotta check the length before
def get_min(graph, key, position=1):
values = graph[key]
if len(values) > position:
return min(values[position])
return -1
graph = {1: [(3, 5), (4, 1), (5, 4)],2:[(5, 9)],3: [(5, 1), (6, 1)],4: [(2, 11), (8, 2)],
5: [(4, 6), (2, 6)],6: [(7, 1)],7: [(5, 7), (2, 1)],8: [(2, 6)],}
for k,v in graph.items():
print(k, get_min(graph, k))
1 => 1
2 => -1
3 => 1
4 => 2
5 => 2
6 => -1
7 => 1
8 => -1
Upvotes: 0