我制作了一个函数,该函数将2d个元素的列表(包含带有2个元素的列表)作为参数,并返回其元素差最大的一个(或多个)元素和其元素差最大的一个(或多个)元素是最小的。例如,给定参数([2,8],[3,4],[2,7],[4,10]),该函数将返回:max =([2,8],[4,10 ]),最小值= [3,4]。
我已经创建了一个可以执行此操作的函数,但是代码相当大,没有添加我要填充的列表作为用户输入参数的部分,我也想这样做。
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=" ")
在我看来,代码对于Python来说太大了。是否有一个简单的快捷方式(内置函数等)使它更短?
答案 0 :(得分:2)
主要思想是跟踪min
和max
值,但也有单独的列表来跟踪每一对
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
驱动程序
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)
输出
('最大结果:',[[2,8],[4,10]])
('最小结果:',[[3,4]])
答案 1 :(得分:1)
如果您想保留所有对,如果它是最大/最小,则可以尝试一下(我已在简化的地方发表了评论):
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)
输出:
max results: [[2, 8], [4, 10]]
min results: [[3, 4]]
这是一种4行解决方案,更具Python风格,但价格更高:
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]
希望对您有所帮助,如有其他问题,请发表评论。 :)