最大化列表中相邻元素之间的差异总和[Python]

时间:2015-08-16 04:57:30

标签: python algorithm dynamic-programming

问题陈述:列表中有N个元素,以最大化相邻元素的绝对差值乘以索引的方式排列它们,

索引从1开始。

(i=2,n=(elements in list))Σ i*abs(list[i-1]-list[i-2])

示例:

输入列表:2 5 4

输出:13

解释

[2,4,5] - > 2 *(2)+ 3 *(1)= 7

[2,5,4] - > 2 *(3)+ 3 *(1)= 9

[5,4,2] - > 2 *(1)+ 3 *(2)= 8

[5,2,4] - > 2 *(3)+ 3 *(2)= 12

[4,5,2] - > 2 *(1)+ 3 *(3)= 11

[4,2,5] - > 2 *(2)+ 3 *(3)= 13

1 个答案:

答案 0 :(得分:0)

您可能不会直接在此论坛中写出问题,并希望人们解决这些问题。这个网站用于修复尝试,而不是制作它们。此外,这个地方不是数学问题,它是编程问题,代码更具体。我建议你去https://math.stackexchange.com/询问数学问题。

但是,同样的规则也适用于此。你必须表明你已经知道如何解决问题,并且你至少已经尝试过。他们会为您提供概念知识,而不是解决问题。就像在线老师一样。

还有一件事,你甚至知道Python是什么吗?既然你把标签。

但是,我确实有办法解决你的问题。您需要先对列表进行排序(我将为您提供Python代码并指导您完成整个过程中的操作)。

numbers = sorted(numbers)

现在,我们的数字从头到尾排序。现在,我们必须成对地取出谁的差异是最大的谁和谁是最少的数字(顺序无关紧要,因为它是绝对值)。这很容易,因为我们已经将数字从最大值排序到最小值。我们需要做的就是从最后挑一个数字,然后从头开始,然后从列表中删除它们,这样我们就有了一个新的开始和结束。像这样。

numbers = [1, 5, 4] #random collection of numbers; you can make it anything really
numbers = sorted(numbers)
import math
pairs = [] #A new list, collection, array, or whatever you want to call it
while len(numbers) == 0 or len(numbers) == 1: #Until there is one element or no elements left:
    pairs.insert(-1, [numbers[0], numbers[-1]]) #-1 means the first element going backwards. 0 means the first element going forwards. Please see below code for better explanation
    del numbers[0] #The first number from our original list of numbers is gone
    del numbers[-1] #The last number from our original list is gone


if pairs: #If our original list of numbers has a number
    pairs.insert(0, [numbers[0]]) #See below code for info on insert()
    del numbers[0]


for pair in pairs:
    numbers.extend(pair) #Instead of having groups of numbers, we now are putting them all into one list. Meaning, instead of something like [[5, 4], [4]] where [5,4] and [4] are separate groups, we have [5, 4, 4] where it is all one group

sum = 0 #The total sum in the end

for x in range(len(numbers) - 1, 1, -2): #Indexes in list start from 0. So to talk about the first number and the last number in a list with 5 numbers you would talk about the 0th element and 4th element (0, 1, 2, 3, 4). We are going from the last to the second element by twos (-2 signifies going backwards). 
    sum += (math.fabs(numbers[x] - numbers[x - 1])) * (x+1) #The formula you specified, keep in mind that our x is '2' in case of the '3rd' element, '0' in case of the first, and so on. math.fabs() is a function that does absolute value

print(numbers,sum, sep = "|||") #Numbers, remember was changed to be the best order it could be. I printed out the numbers, then a |||, then the sum

请安装Python 3.4以运行此程序

我在程序中几次使用'insert'命令。在insert(-1, [numbers[0], numbers[-1]]中,我将[first_number, last_number]插入到列表的最后部分。这可能有点过头,谷歌周围有点你会理解。这就是我做的事情(1年前):P。保持心态:数字从最小到最大排序。