2017-04-01 58 views
-1

這似乎是一個令人尷尬的簡單概念,但我不明白爲什麼這個for循環正在工作的方式。問題是簡單地問「給定一個二進制數組,找到這個數組中連續1的最大數目。」這對循環連續整數是如何工作的?

def main(nums): 
count = 0 
for num in nums: 
    if num == 1: 
    count+=1 
    else: 
    count = 0 
main([1,1,0,1,1,1,0,0,1,1,1,1,1]) 

我的問題是,爲什麼這個循環工作?我期望循環打印1的總數。

+0

爲什麼你需要的'else'?此外,縮進不是很清楚 –

+1

@MosesKoledoye如果我拿出else語句,那麼它將所有1的計數加起來 –

回答

2

這是行不通的。

您不能指望所有1的總和,因爲當循環找到零時,它會重置計數器(「else」部分)。

但是,您的代碼沒有執行預期的操作,在列表末尾添加一個零,您將很容易看到代碼失敗。

要做到你的要求,在不改變你的代碼太多,試試這個

def main(nums): 
    count = maxcount = 0 
    for num in nums: 
     if num == 1: 
      count+=1 
     else: 
      maxcount=max(maxcount, count) 
      count = 0 
    return maxcount 
print(main([1,1,0,1,1,1,1,1,1,0,0,1,1,1,1,0,1])) 

戴夫

1

所不同的是,一旦它看到一個零,它設置的count值回落到零,說這是連續看到那些0。這段代碼實際上不起作用 - 它只能在這個輸入上運行,因爲最長的序列在列表的最後。

一個更好的做法是將current_group的長度和highest_total計數存儲在一起。

0

這可能很難相信,但會不會是你想知道爲什麼這個循環在所有工作的原因是你不熟悉Python遍歷列表中的所有元素的能力,不需要任何計數器變量增加它的價值?

[1,1,0,1,1,1,0,0,1,1,1,1,1]

是在Python一種陣列的存儲的多個數值。

這裏是一些「僞碼」僅用於證明"for num in nums"意味着在Python(在編程方面在其它 語言不支持迭代在一個列表/陣列的元件)說明目的:

noOfValuesIn_nums = lengthOf/sizeOf(nums) 
for i = 0 to noOfValuesIn_nums do: 
    # get i=th value from 'nums' and put it to a variable named 'num': 
    num = nums[i] 
    ... 

順便說一句:在問題中提供的環路給出了提供例如所期望的結果: 主([1,1,0,1,1,1,0,0,1,1,1,1,1 ]) 但不會在另一個工作,如這裏演示的:

def main(nums): 
    count = 0 
    for num in nums: 
     if num == 1: 
      count+=1 
     else: 
      count = 0 
    return count 

print(main([1,1,1,1,1,1,0,0,1,1,1,0,1])) 
# it prints 1 instead of 6 

找到下面的代碼的人 解決了最長連續序列的任務:

def main1(nums): 
    count = 0 
    maxOnes = 0 
    for num in nums: 
     if num == 1: 
      count+=1 
     else: 
      if count > maxOnes: 
       maxOnes = count 
      count = 0 
    return maxOnes 
print(main1([1,1,1,1,1,1,0,0,1,1,1,0,1])) 
# gives 6