根据其他列表和其他条件修改列表

时间:2020-04-03 14:58:18

标签: python arrays python-3.x

我已删除上一个问题,并将其重写

我有2个大小为n的列表(假设为5):

  1. 列表a由非零随机整数组成

  2. 列表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

1 个答案:

答案 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