[英]Editing the sum of array elements to equal a value in Python
我有一个清单。 我希望元素的总和等于n
。 由于这个原因,我列表的最后一个元素是可变的。 例如:
L=[1,2,3,4]
n=5
for first element = 1 < 5 resume
for second element = (1+2) < 5 resume
for third element = (1+2+3) > 5 break / for equal
Lnew[1,2,2]
或者
L=[3,4,5]
n=6
for first element = 3 < 5 resume
for second element = (3+4) > 5 break / for equal
Lnew[3,3]
那是伪代码,不是python,老实说我不太明白你写的什么
python 中的解决方案是
my_array = [......]
N = 999
my_array[-1] = N-sum(my_array[:-1])
将最后一个元素更改为 N 减去除最后一个元素之外的所有元素的总和
如果到目前为止的总和小于n
,则迭代列表中的每个值 append 。 如果没有,append 的区别和break
:
L = [3,4,5]
n = 6
s = 0 # sum so far, increases in the for-loop
Lnew = [] # empty list, values are appended in for-loop
for i in L:
if i + s <= n:
# if the value plus the sum so far is smaller than n: append to list and increase s
Lnew.append(i)
s += i
else:
# else, append difference and stop the for-loop
Lnew.append(n - s)
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.