PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] How to find sorted 'means of indexes' of two lists?

 November 02, 2022     indexing, list, python, ranking, sorting     No comments   

Issue

The task I have is as shown. Given two lists of ints, such as:

lst1 = [4,1,3,5,2]
lst2 = [1,3,5,2,4]

I want to get the mean of the ints indexes. For example, the int 4 will have indexes of 0 and 3, thus will have an index mean of 1.5. Similarly, int 1 will have an index mean of 1. I want to then have all ints in a list, sorted by their 'index mean'. The result should be:

result = [1, 3, 4, 5, 2]

as their means are 0.5, 1.5, 2, 2.5, and 3.5, respectively.

What is a fast pythonic way of doing this without going through some complicated iterations? All help is appreciated!


Solution

>>> lst1 = [4,1,3,5,2]
>>> lst2 = [1,3,5,2,4]
>>> sorted(lst1, key=lambda n: lst1.index(n) + lst2.index(n))
[1, 3, 4, 5, 2]

Note that finding the actual average (i.e. dividing the sum by 2) isn't necessary since you're using the values as sort keys; as long as they have the same comparison results as the averages (which they will since each sum is the average times a constant factor of 2) you get the correct result.

For a more efficient solution, you'd build a dictionary so you only need to iterate through each list once to sum up all the indices:

>>> avg_indices = {n: 0 for n in lst1}
>>> for a in (lst1, lst2):
...     for i, n in enumerate(a):
...         avg_indices[n] += i
...
>>> sorted(lst1, key=avg_indices.get)
[1, 3, 4, 5, 2]

Building lists of indices (and taking the actual average) would become necessary if you didn't have the same number of occurrences of each item across the lists.



Answered By - Samwise
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing