随机选择列表中的元素,然后反复查找其在随机选择的元素之间(max-min)的差异,最后打印出最小差异
我认为以上内容几乎可以解释所有内容,但让我重新措辞。
我构建了一个代码,尝试根据输入k随机选择列表中的几个元素。选择少量元素后,我将计算max(list)-min(list)之间的差。
示例;
a=[1,2,3,4,5]
max(a) - min(a) = 4
然后将这个值保存到字典中。但是,字典是要存储的(也许其他方法更好或更快速)。
我将继续基于k选择随机元素,并找出差异。最后,它将比较所有这些差异并将最低的差异存储到字典中。
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}
或印刷版本:
答案 0 :(得分:1)
我认为这将为您提供所需的东西。
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]