2016-11-30 129 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)