Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 842693
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T06:00:16+00:00 2026-05-15T06:00:16+00:00

Let’s say I have a list of objects. (All together now: I have a

  • 0

Let’s say I have a list of objects. (All together now: “I have a list of objects.”) In the web application I’m writing, each time a request comes in, I pick out up to one of these objects according to unspecified criteria and use it to handle the request. Basically like this:

def handle_request(req):
    for h in handlers:
        if h.handles(req):
            return h
    return None

Assuming the order of the objects in the list is unimportant, I can cut down on unnecessary iterations by keeping the list sorted such that the most frequently used (or perhaps most recently used) objects are at the front. I know this isn’t something to be concerned about – it’ll make only a miniscule, undetectable difference in the app’s execution time – but debugging the rest of the code is driving me crazy and I need a distraction 🙂 so I’m asking out of curiosity: what is the most efficient way to maintain the list in sorted order, descending, by the number of times each handler is chosen?

The obvious solution is to make handlers a list of (count, handler) pairs, and each time a handler is chosen, increment the count and resort the list.

    def handle_request(req):
        for h in handlers[:]:
            if h[1].handles(req):
                h[0] += 1
                handlers.sort(reverse=True)
                return h[1]
        return None

But since there’s only ever going to be at most one element out of order, and I know which one it is, it seems like some sort of optimization should be possible. Is there something in the standard library, perhaps, that is especially well-suited to this task? Or some other data structure? (Even if it’s not implemented in Python) Or should/could I be doing something completely different?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T06:00:17+00:00Added an answer on May 15, 2026 at 6:00 am

    Python’s sort algorithm, timsort, is pretty magical: if your listed is sorted except for one element, it will intrinsically (discover and) use that fact, sorting in O(N) time. (Josh Bloch, the Java guru, was so impressed by a presentation about timsort’s performance characteristics that he started coding it for Java on his laptop — it’s supposed to become Java’s standard sort pretty soon). I’d just do a sort after each locate-and-increment-count, and very much doubt that other approaches can beat timsort.

    Edit: the first alternative that comes to mind, of course, is to possibly “shift up” just the item whose count you’ve just incremented. But first, a little optimization to avoid copying handlers…):

    def handle_request(req):
        for h in handlers:
            if h[1].handles(req):
                h[0] += 1
                handlers.sort(reverse=True)
                break
        else:
            return None
        return h[1]
    

    now, the “shift up” variant

    def handle_request(req):
        for i, h in enumerate(handlers):
            if h[1].handles(req):
                h[0] += 1
                for j in reversed(range(i+1)):
                    if handlers[j][0] <= h[0]:
                        break
                if j < i:
                    handlers[j+1:i+1] = handlers[j:i]
                    handlers[j] = h
                break
        else:
            return None
        return h[1]
    

    I can imagine patterns of access where this approach might save a little time — for example, if the distribution was so skewed that most hits were in handlers[0], this would do little work beyond one comparison (while sort needs about N of them even in the best case). Without representative samples of your access patterns, I can’t confirm or disprove this!-)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have two assemblies: BusinessLogic and Web. BusinessLogic has an application setting
Let's say I have a sortable list like this: $(.song-list).sortable({ handle : '.pos_handle', axis
Let me frame it this way.. Say I have an application server running on
Let's say, I have an application that access(read/write) the file system(files inside application), Active
Let's say I'm creating an OpenGL game in C++ that will have many objects
Let's say I have a large amount of files, say 20GB worth, all encrypted
Let's say I have two objects, Master and Slave . Slave has a method
Let's say I have 2 windows in my application, and two classes responsible for
Let's say I'm writing a Windows Forms (.NET Framework 3.5) application which shows the
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.