2017-02-09 24 views
0

這是python3整個代碼:值沒有改變什麼它應該(9號線)

def rainwater(array): 
    max_value = max(array) 
    count = 0 
    for a in range(0, max_value): 
     temp = array 
     for i in range(0, len(temp)): 
      if temp[i] >= 1: 
       print(temp) 
       temp[i] = 1 # somehow this line always changes temp[i] to 0 instead of 1 
       array[i] = array[i] - temp[i] 

      array = temp 

     for i in range(0, len(temp)): 
      if temp[i] == 1: 
       del temp[:i] 
       break 
     for i in range(0, len(temp) - 1, -1): 
      if temp[i] == 1: 
       del temp[i:] 
       break 
     if len(temp) <= 1: 
      return count 
     for i in range(0, len(temp)): 
      if temp[i] == 0: 
       count = count + 1 
    return count 


# driver program -> should return 6 

print(rainwater([0,1,0,2,1,0,1,3,2,1,2,1])) 

上線9.不知道如何分類出現此問題的問題,但我不能爲我的生活弄清楚這裏缺少的東西。提前致謝。

+0

請檢查並接受答案 –

回答

1

問題

問題是與分配臨時的陣列

隨着temp = array,你實際上並不有兩個列表。分配只是將引用複製到列表中,而不是實際列表中,因此temp和array在分配後都引用相同的列表。

temp = array 
for i in range(0, len(temp)): 
    if temp[i] >= 1: 
     print(temp) 
     temp[i] = 1 # somehow this line always changes temp[i] to 0 instead of 1 
     array[i] = array[i] - temp[i] 

    array = temp 

在上面的代碼,更改爲temp[i]改變array[i], 所以

temp[i] = 1      # sets temp[i] = array[i] = 1 
    array[i] = array[i] - temp[i]  # array[i] = tempa[i] = 1-1 

因此溫度[i]是0而不是1

如何解決

您可以使用copy,deepcopyslicing到陣列複製到臨時

這裏是工作的更新的代碼,用於slicing

代碼

def rainwater(array): 
    max_value = max(array) 
    count = 0 
    for a in range(0, max_value): 
     temp = array[:] 
     for i in range(0, len(temp)): 
      if temp[i] >= 1: 
       print(temp) 
       temp[i] = 1 # somehow this line always changes temp[i] to 0 instead of 1 
       array[i] = array[i] - temp[i] 

      array = temp[:] 

     for i in range(0, len(temp)): 
      if temp[i] == 1: 
       del temp[:i] 
       break 
     for i in range(0, len(temp) - 1, -1): 
      if temp[i] == 1: 
       del temp[i:] 
       break 
     if len(temp) <= 1: 
      return count 
     for i in range(0, len(temp)): 
      if temp[i] == 0: 
       count = count + 1 
    return count 


# driver program -> should return 6 

print(rainwater([0,1,0,2,1,0,1,3,2,1,2,1])) 
1

此行的值設置爲0:

array[i] = array[i] - temp[i] 

原因是數組和temp是相同的對象。所以x-x總是爲零。

我認爲你假定在第5行代碼,這使得數組的副本:

temp = array 

但事實並非如此。這使temparray都引用相同的數組。如果你真的想要的數組的副本,這樣做:

temp = array[:] 

此外,您可能需要修正線11爲好,如果你是一個副本。

我建議您閱讀更多關於通過引用和按值傳遞變量的信息。

相關問題