2016-11-30 130 views
-1

所以这是一个函数,它需要两个排序列表。它需要一个负数(欠钱的人)和一个正数(欠钱的人)的清单。然后,它从负面清单中偿还欠款的人。嵌套的while循环问题

实施例:

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:列表索引超出范围

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

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

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

回答

1

既然你递增指数i,并在内环j,你需要把相应的条件也在第一内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 
+0

谢谢trincot! – WhitneyChia

+0

不客气;-) – trincot

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)