最大化列表中的空间

时间:2018-06-26 02:10:42

标签: python python-3.x list

所以我想看看是否有可能让我最大化列表中的空间。例如:

[0]

每个步骤的过程:

lists = [3, 3, 3, 3, 3]

Maximum Value = 4 #from user input

Output = [3, 0, 4, 4, 4]

基本上,代码应从列表的后面开始,并在列表中的每个值后面填充空格,直到其中一个值等于4或0或到达列表的开头为止。

最后一件事: 这应该适用于任何列表长度,即使最后一个数字之后为0,也是如此。例如:

Start: [3, 3, 3, 3, 3] #start
       [3, 3, 3, 2, 4] #takes 1 number from lists[3] and puts it in lists[4] so that that is equal to 4
       [3, 3, 1, 4, 4] #takes 2 numbers from(since 4 - lists[3] = 2 lists[2] and puts it in lists[3]
Finish:[3, 0, 1, 4, 4] #puts 3 numbers from lists[1] and puts them in lists[2](4 - lists[2] = 3) and now that there is a zero it should stop the program

2 个答案:

答案 0 :(得分:2)

您不需要所有这些中间步骤。您可以通过简单的除法和余数计算直接生成列表。

>>> l = [3, 3, 5, 2, 7, 2, 3, 0, 0, 0, 0, 4]
>>> m = 4
>>> [m] * (sum(l) / m) + [sum(l) % m] + [0] * (len(l) - sum(l) / m - 1)
[4, 4, 4, 4, 4, 4, 4, 1, 0, 0, 0, 0]
>>>

答案 1 :(得分:0)

这是示例代码,也许有更好的方法。

lis = [3, 3, 5, 2, 7, 2, 3, 0, 0, 0, 0, 4]

MaximumValue = 4
start_index = 0
for i,v in enumerate(lis):
  start_index = i
  if v == 0:
    start_index = i - 1
    break

for i in range(start_index, 0, -1):
  diff = MaximumValue - lis[i]
  if diff >= 0:
    lis[i] += diff
    lis[i-1] -= diff
  if lis[i-1] == 0:
    break

print(lis)

输出:

[1, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 4]