2

I made a function which takes a list of 2d elements(containing lists with 2 elements) as an argument and returns the element(or elements) whose elements' difference is the biggest and the one(or more) whose elements' difference is the smallest. For example, given an argument ([2,8],[3,4],[2,7],[4,10]), the function would return: max=([2,8], [4,10]), min=[3,4].

I have made a function that does that, but the code is rather big, without me adding the part which I fill the list to be passed as argument with user input,which I also want to do.

def maxminIntervals(lst):
 mx=lst[0][1]-lst[0][0]
 mn=mx
 count_max=count_min=0

 max=[]
 min=[]
 print(max,min)
 print(mx,mn)
 for element in lst:
    y=element[1]-element[0]
    if y>mx:
        max=[]
        max.append(element)
        count_max=0
        mx=y
    elif y==mx:
        max.append(element)
        mx=y
        count_max+=1
    if y<mn:
        min=[]
        min.append(element)
        count_min=0
        mn=y
    elif y==mn:
        min.append(element)
        mn=y
        count_min+=1
    print(y)
 print("Max=",end='')
 if count_max>0:
        print("(",end=" ")
 for i in max:
    print(i,end=' ')
 if count_max>0:
        print(")",end=" ")
 print("\n")
 print("Min=",end=' ')
 if count_min>0:
        print("(",end=" ")
 for i in min:
    print(i,end=' ')
 if count_min>0:
    print(")",end=" ")

It seems to me the code is too big for Python. Is there a simple shortcut(built-in function, etc) to make it shorter?

Georgy90
  • 155
  • 2
  • 12

2 Answers2

2

if you want to keep the all the pairs, if it is the maximun/minimun, you can try this (I have commented where I simplify it):

def maxminIntervals(lst):
    max_diff, min_diff = float('-inf'), float('inf')
    max_results, min_results = [], []
    # for loop and unzip pairs to num1, num2
    for num1, num2 in lst:
        # define diff to compare min and max
        diff = num2 - num1
        # append to max_results
        if diff == max_diff:
            max_results.append([num1, num2])
        # update a new max_results
        elif diff > max_diff:
            max_diff = diff
            max_results = [[num1, num2]]

        # append to min_results
        if diff == min_diff:
            min_results.append([num1, num2])
        # update a new min_results
        elif diff < min_diff:
            min_diff = diff
            min_results = [[num1, num2]]
    return max_results, min_results

def test():
    lst = ([2, 8], [3, 4], [2, 7], [4, 10])
    max_results, min_results = maxminIntervals(lst)
    print('max results:', max_results)
    print('min results:', min_results)

output:

max results: [[2, 8], [4, 10]]
min results: [[3, 4]]

Here is a 4-line solution, more pythonic, but cost more:

from collections import defaultdict
from operator import itemgetter

def maxminIntervals2(lst):
    diff_dict = defaultdict(list)
    for pair in lst:
        diff_dict[pair[1] - pair[0]].append(pair)
    return max(diff_dict.items(), key=itemgetter(0))[1], min(diff_dict.items(), key=itemgetter(0))[1]

Hope that will help you, and comment if you have further questions. : )

recnac
  • 3,744
  • 6
  • 24
  • 46
2

The main idea is to keep track of the min and max values but also have separate lists to keep track of each pair

def maxMinIntervals(lst):
    maximum, minimum = [], []
    max_value, min_value = float('-inf'), float('inf')
    for pair in lst:
        value = abs(pair[1] - pair[0])
        if value > max_value:
            max_value = value
            maximum = []
            maximum.append(pair)
        elif value == max_value:
            maximum.append(pair)
        if value < min_value:
            minimum = []
            minimum.append(pair)
            min_value = value
        elif value == min_value:
            minimum.append(pair)
    return maximum, minimum 

Driver

input_list = [[2,8], [3,4], [2,7], [4,10]]
max_ans, min_ans = maxMinIntervals(input_list)
print('maximum results: ', max_ans)
print('minimum results: ', min_ans)

Output

('maximum results: ', [[2, 8], [4, 10]])

('minimum results: ', [[3, 4]])

Community
  • 1
  • 1
nathancy
  • 42,661
  • 14
  • 115
  • 137