您可能不会直接在这个论坛上写下问题并期望人们解决它们。本网站用于修复尝试,而不是进行尝试。此外,这个地方不是数学问题,而是编程问题,更具体的代码。我建议你去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(-1, [numbers[0], numbers[-1]] 中,我将[first_number, last_number] 插入到列表的最后一部分。这可能有点过头了,谷歌一下,你会明白的。反正我就是这样做的(1年前):P。记住:数字从小到大排序。