首页 > 解决方案 > 重复选择列表中的项目并根据列表的最大最小值找到最小差异

问题描述

随机选择列表中的元素,然后重复找到随机选择的元素之间的差异(最大 - 最小),最后打印出最小差异

我认为我的上述几乎解释了一切,但让我改写一下。

我构建了一个代码,尝试根据输入 k 随机选择列表中的几个元素。选择几个元素后,我将计算 max(list) - min(list) 之间的差异。

例子;

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

max(a) - min(a) = 4

然后这个值将被保存到字典中。但是,字典是要存储的(也许其他方法更好或更快)。

我将继续根据 k 选择随机元素并找出差异。最后,它将比较所有这些差异并将 LOWEST 差异存储到字典中。

import random

maximum_dict = dict()
maximum_dict["m"] = 1000000000

def maxMin(k, arr):
    list_temp = random.sample(arr, k)
    maximum = int(max(list_temp) - min(list_temp))
    for x, y in maximum_dict.items():
        while maximum < y:
            if maximum < y:
                maximum_dict["m"] = maximum
            else:
                while maximum > y:
                    list_temp = random.sample(arr, k)
                    maximum = int(max(list_temp) - min(list_temp))
                    if maximum < y:
                        maximum_dict["m"] = maximum


    return maximum

def p():
    print(maximum_dict.values())

if __name__ == "__main__":
    arr = [10,100,300,200,1000,20, 30]
    k = 3
    print(maxMin(k, arr))
    p()

我当前的输出:

它随处可见,它应该只是一个输出,因为那将是最低的。

我的预期输出:

字典 ={"m":20}

或印刷版:

标签: python

解决方案


我认为这会给你你正在寻找的东西。

from itertools import combinations

arr = [10, 100, 300, 200, 1000, 20, 30]

b = tuple(combinations(arr, 3))

print("The various combinations look like this")
for i in b:
    print(i)

res = [max(i)-min(i) for i in b]
print(
    f"The list shows the difference b/w max and min for every combination\n{res}")
print(f"The lowest difference = {min(res)}")

输出:

The various combinations look like this
(10, 100, 300)
(10, 100, 200)
(10, 100, 1000)
(10, 100, 20)
(10, 100, 30)
(10, 300, 200)
(10, 300, 1000)
(10, 300, 20)
(10, 300, 30)
(10, 200, 1000)
(10, 200, 20)
(10, 200, 30)
(10, 1000, 20)
(10, 1000, 30)
(10, 20, 30)
(100, 300, 200)
(100, 300, 1000)
(100, 300, 20)
(100, 300, 30)
(100, 200, 1000)
(100, 200, 20)
(100, 200, 30)
(100, 1000, 20)
(100, 1000, 30)
(100, 20, 30)
(300, 200, 1000)
(300, 200, 20)
(300, 200, 30)
(300, 1000, 20)
(300, 1000, 30)
(300, 20, 30)
(200, 1000, 20)
(200, 1000, 30)
(200, 20, 30)
(1000, 20, 30)
The list shows the difference b/w max and min for every combination
[290, 190, 990, 90, 90, 290, 990, 290, 290, 990, 190, 190, 990, 990, 20, 200, 900, 280, 270, 900, 180, 170, 980, 970, 80, 800, 280, 270, 980, 970, 280, 980, 970, 180, 980]
The lowest difference = 20

[Process exited 0]

推荐阅读