我已删除上一个问题,并将其重写
我有2个大小为n
的列表(假设为5):
列表a
由非零随机整数组成
列表b
由符合以下条件的随机非负整数组成:
i
个元素大于或等于第i+1
个元素f
(假设为10)在这里,我要修改列表b
,以便除了上述两个条件之外,它还符合以下条件:
i
个元素都小于或等于列表i
的第a
个元素如果由于某些原因无法同时满足所有三个条件,则可能放宽关于总和等于f
的准则,并变成f-a
,其中也减去a
从列表b
的最右边元素开始,而a
是可能的最小整数(请参见最后一个示例)
一些示例(r
是修改后的列表b
):
a = [6, 7, 14, 16, 5]
b = [8, 2, 0, 0, 0]
r = [6, 4, 0, 0, 0]
a = [10, 1, 14, 16, 5]
b = [8, 2, 0, 0, 0]
r = [8, 1, 1, 0, 0]
a = [10, 5, 14, 16, 5]
b = [8, 2, 0, 0, 0] # here, b is already complying to all criteria and result should not change
r = [8, 2, 0, 0, 0]
# another example where this list is of size 14 with `f` being also 14
a = [7, 5, 14, 16, 5, 7, 203, 22, 10, 4, 5, 8, 12, 9]
b = [8, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
r = [7, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
a = [5, 1, 1, 1, 1]
b = [8, 2, 0, 0, 0]
r = [5, 1, 1, 1, 1]
我的numpy
方法适用于b
不需要任何编辑的情况:
a = [10, 5, 14, 16, 5]
b = [8, 2, 0, 0, 0]
def edit(a, b):
a_ = np.array(a)
b_ = np.array(b)
criteria_check = (a_[:len(b_[b_>0])] >= b_[b_>0])
if criteria_check.all():
return b
else:
pass
edit(a, b)
[8, 2, 0, 0, 0]
添加另一种方法来解决numpy中的最后一个示例案例:
a = [5, 1, 1, 1, 1]
b = [8, 2, 0, 0, 0]
a = np.array(a)
b = np.array(b)
def edit2(f, s):
diff = f - s
s[(s + diff).cumsum()<sum(s)] = (s + diff)[(s + diff).cumsum()<sum(s)]
return s
答案 0 :(得分:1)
此解决方案适用于您的所有测试用例:
def solve(a, b):
f = 0
for i in range(len(a) - 1):
if (a[i] < b[i]):
b[i+1] += (b[i] - a[i])
b[i] = a[i]
f += a[i]
else:
f += b[i]
x = 0
if sum(b) > sum(a):
x = sum(b) - sum(a)
b[-1] = sum(b) - f - x
return b