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 972507
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T03:08:07+00:00 2026-05-16T03:08:07+00:00

I’m completely new to Python and while trying various random bits and pieces I’ve

  • 0

I’m completely new to Python and while trying various random bits and pieces I’ve struck upon a problem that I believe I’ve "solved", but the code doesn’t feel right – I strongly suspect there is going to be a better way to get the desired result.

FYI – I’m using whatever the latest version of Python 3 is, on Windows.

Problem definition

Briefly, what I’m doing is sorting a list of pairs, such that the pairs containing the elements that appears in the fewest pairs are sorted to the front.

The pairs are in the form [i,j] with 0 <= i <= j < n, where n is a known maximum value for the elements. There are no duplicate pairs within the list.

The count of an element i is a simple count of the number of pairs (not pair elements) in the forms [i,j],[j,i] and [i,i] where j is any value that results in a valid pair.

In the sorted result, a pair [i,j] should appear before a pair [k,l] if count(i) < count(k) or count(i) == count(k) and count(j) < count(l) (If count(j) == count(l) the two can be in either order – I’m not bothered about the sort being stable, would be a bonus though).

In the sorted result, a pair [i,j] should appear before a pair [k,l] if
min(count(i),count(j)) < min(count(k),count(l)) or
min(count(i),count(j)) == min(count(k),count(l)) and max(count(i),count(j)) < max(count(k),count(l)).
In otherwords, if the pair is [0,1] and 1 has a count of one, but 0 has a count of four hundred, the pair should still be at (or at least very near) the front of the list – they need sorting by the least frequent element in the pair.

Here’s a contrived example I’ve built:

input   [[0,0],[1,2],[1,4],[2,2],[2,3],[3,3],[3,4]]

Here’s the individual element counts and the source pairs they come from:

0: 1   [0,0]
1: 2   [1,2],[1,4]
2: 3   [1,2],[2,2],[2,3]
3: 3   [2,3],[3,3],[3,4]
4: 2   [1,4],[3,4]

And here’s the result, along with the pair scores:

output: [[0,0],[1,4],[1,2],[3,4],[2,2],[2,3],[3,3]]
scores:   1     1-2   1-3   2-3   3     3     3

Here, 0 has a count of one (it appears in one pair, albeit twice) so comes first. 1 has a count of two, so appears second – with [1,4] before [1,2] because 4 has a count of two and 2 has a count of three, et cetera.

My current solution

As said, I believe this implimentation works accurately, but it just feels that there must be a better way to go about doing this. Anyway, here’s what I’ve got so far:

#my implementation uncommented to reduce post size, see history for comments
def sortPairList( data , n ):
    count = []
    for i in range(0,n):
        count.append( 0 )

    #count up the data
    for p in data:
        count[p[0]] += 1
        if p[1] != p[0]:
            count[p[1]] += 1

    maxcount = 0
    for i in range(0,n):
        if count[i] > maxcount:
            maxcount = count[i]

    def elementFrequency(p):
        if count[ p[0] ] < count[ p[1] ]:
            return count[ p[0] ] + float(count[ p[1] ]) / (maxcount+1)
        else:
            return count[ p[1] ] + float(count[ p[0] ]) / (maxcount+1)

    data.sort( key=elementFrequency )

Any suggestions on a more "Python" way of doing this?
Or anything that’s wrong with my current attempt?

New Test Case (see answer’s comments)

input:    [[0,0],[0,3],[0,5],[0,7],[1,1],[1,2],[1,8],[2,4],[2,5],[3,4],[3,5],[3,9],[4,4],[4,7],[4,8],[6,8],[7,7],[7,9],[8,9]]
expected: [[6,8],[1,1],[1,2],[2,5],[0,5],[1,8],[3,5],[3,9],[7,9],[8,9],[2,4],[0,0],[0,3],[0,7],[7,7],[3,4],[4,7],[4,8],[4,4]]
  • 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-16T03:08:08+00:00Added an answer on May 16, 2026 at 3:08 am

    I would probably use a Counter (needs Python ≥2.7 or ≥3.1) for tallying.

    from collections import Counter
    from itertools import chain
    def sortPairList2(data):
        tally = Counter(chain(*map(set, data)))
        data.sort(key=lambda x: sorted(tally[i] for i in x))
    

    Note that:

    1. You can create an anonymous function with lambda. For example,

      >>> c = 4
      >>> a = lambda p: p - c
      >>> a(7)
      3
      
    2. The sort key need not be a number. Anything comparable can be used as the return value of the key function. In my code, a list is used for ordering.

    3. There are many simpler idioms in Python for your original code.

      • The count can be initialized using count = [0] * n instead of that loop.
      • The maxcount can be obtained with the max function. maxcount = max(count)
    4. List comprehension is used a lot in Python. If your target is to transform an iterable into another iterable, prefer comprehension over loops.

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

Sidebar

Ask A Question

Stats

  • Questions 489k
  • Answers 489k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This is a data issue. The live environment contains data… May 16, 2026 at 8:55 am
  • Editorial Team
    Editorial Team added an answer the lexer for scala throws blankspaces away. try override val… May 16, 2026 at 8:55 am
  • Editorial Team
    Editorial Team added an answer Uopon further investigation I found my mistake. I should have… May 16, 2026 at 8:55 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

No related questions found

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.