嵌套While循环问题

时间:2016-11-30 22:03:19

标签: python while-loop

因此,这是一个需要两个排序列表的函数。它需要一个负数列表(欠钱的人)和一个正数列表(欠钱的人)。然后,它会从负面清单中支付欠款的人。

示例:

negatives = [-55.774, -45.884, -40.754, -35.694, -33.734, -29.024, -25.114, -16.144, -14.014, -5.874, -5.554]
positives = [43.936, 42.276, 33.756, 31.116, 30.456, 27.616, 21.526, 18.276, 13.176, 12.376, 11.966, 8.566, 8.486, 4.036]

我的过程中的第一步是负数[0]将支付正数[0],43.936,然后它支付部分正数[1],直到自身负数[0]为0,然后进入负数[1]并且还清了对积极因素的欠款[1]。我只想尝试迭代这个过程。这就是我所拥有的:

def pay_balances(x, y):
    i = 0
    j = 0
    while i < len(x) and j < len(y):
        while abs(x[i]) > abs(y[j]) and abs(round(x[i],4)) != 0:
            print y[j]
            x[i] = x[i] + y[j]
            y[j] = 0
            j += 1
            print i, j
        while abs(x[i]) < abs(y[j]) and abs(round(x[i],4)) != 0:
            print -x[i]
            y[j] = y[j] + x[i]
            x[i] = 0
            i += 1
            print i, j

所以,如果你跑......

pay_balances(negatives, positives)

由于IndexError:list index超出范围

,这最终会中断

问题是当我们是列表的末尾时,我的j值= 14,这是我希望一切都停止的时候。它似乎留在循环中,即使我有这条线,我认为会杀死它:

while i < len(x) and j < len(y):

我做错了什么?一如既往地感谢!!

2 个答案:

答案 0 :(得分:1)

由于您在内部循环中递增索引ij,您需要将相应的条件也放在第一个内部while循环中,并添加一个退出点 - 方式:

while i < len(x) and j < len(y):
    while j < len(y) and abs(x[i]) > abs(y[j]) and abs(round(x[i],4)) != 0:
        print y[j]
        x[i] = x[i] + y[j]
        y[j] = 0
        j += 1
        print i, j
    if j >= len(y):
        break
    while i < len(x) and abs(x[i]) < abs(y[j]) and abs(round(x[i],4)) != 0:
        print -x[i]
        y[j] = y[j] + x[i]
        x[i] = 0
        i += 1
        print i, j

答案 1 :(得分:0)

我认为这段代码通过一个循环生成你想要的东西:

def pay_balances(x, y):
i = 0
j = 0
while x[-1] != 0 and y[-1] !=0:   
    if abs(x[i]) > abs(y[j]): 
        x[i] = x[i] + y[j]
        y[j] = 0
        j += 1  
    elif abs(x[i]) < abs(y[j]):
        y[j] = y[j] + x[i]
        x[i] = 0
        i += 1         
print x, y
return sum(x) + sum(y)