Finding min value in a dictionary in O(1) time Python

victor__von__doom :

I need a way to find the minimum value in a dictionary full of Node objects in O(1) time, or really any sublinear time, if possible.

Here's an example of what I'd need:

'''
 Nodes have 4 attributes: 
  - stack
  - backwards
  - forwards
  - total_score
'''
dict = {str(Node1.stack): Node1, 
        str(Node2.stack): Node2, ... } # note that keys are the stacks as strings

key, smallest = min(frontier.items(), key=lambda pair: pair[1].total_score)
( ^^^ something better than this! ^^^ )

The last line above (key, smallest ... ) is what I have so far. It works fine, but it's too slow. I read online that the min() function takes O(n) time. I have a lot of Nodes to process, so something faster would be amazing.

edit Should have mentioned before, but this is running inside an A* algorithm - frontier is updated dynamically. The operations I need to be able to do are:

  1. Find minimum in O(1), or at least < O(n)
  2. Update values of specific elements quickly
  3. Access attributes easily
frodo2975 :

It's impossible to get the min value from a dictionary in O(1) time because you have to check every value. However, you can do a fast lookup if you store your data in a heap or a sorted tree, where the data is sorted by value. Trees generally give you insertion and search times of O(log n).

If you literally only need the min value of your data and you don't ever need to look up other values, you could just create a minValue variable that you keep updated every time you insert or remove items.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=4023&siteId=1