Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Treverse list of tuples to compare and report min, max

My previous question was not understood, so I rephrase and post this one.
I have a list of tuple for (class, n_class_examples) like this:

my_list = (0, 126), (1, 192), (2, 330), (3, 952) ]

So I am interested in generating a function, that takes in such a list, compare each tuple against all others, and in each case reports which class has smaller number of samples (min_class), and which has the larger number of samples (max_class).

def get_min_max_class(current_list):
    for tn, tn+1: # tn -> 1-tuple, tn+1 any other tuple not tn
        if tn[1] < tn+1[1]
            smaller_class = tn[0]
            larger_class = tn+1[0]
        smaller_class = tn+1[0]
        larger_class = tn[0]
    return # smaller, larger of the 2 compared in each case

So that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

get_min_max_class(my_list)
# would perform the comparison like so:
(0, 126) v (1, 192) -> min_class = 0, max_class = 1 # in this case
(0, 126) v (2, 330) -> min_class = 0, max_class = 2 # and in this case
(0, 126) v (3, 952) -> min_class = 0, max_class = 3 # and here ..
(1, 192) v (2, 330) -> min_class = 1, max_class = 2 # ...
(1, 192) v (3, 952) -> min_class = 1, max_class = 3
(2, 330) v (3, 952) -> min_class = 2, max_class = 3

Forgive my definition of function, but I want the function to iteratively compare those items, each time, report which is larger and which is smaller.

>Solution :

Iterate over the list of pairs generated by itertools.combintions, the process each pair individually using min and max.

from itertools import combinations
from operator import itemgetter

first = itemgetter(0)
second = itemgetter(1)

def get_min_max_class(current_list):
    for pair in combinations(current_list, 2):
        p0, p1 = pair
        min_class = first(min(pair, key=second))
        max_class = first(max(pair, key=second))
        print(f'{p0} v {p1} -> min_class = {min_class}, max_class = {max_class}')

get_min_max_class(my_list)

If you want to return a list of results, rather than simply printing a report, you’ll have to define what exactly you want to return.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading