2016-04-14 55 views
2

我目前正在編寫一個python代碼,試圖找出四位數的數字加起來到一個特定的值。我的代碼如下:數字總和代碼 - 返回0的數組

def findSum(): 
    target = 0; 
    checkno = 1000; 
    comboSum = []; 
    sumArray = []; 
    while target<=36 : 
    while checkno<10000 : 
     digitSum = int(str(checkno)[0]) + int(str(checkno)[1]) + int(str(checkno)[2]) + int(str(checkno)[3]); 
     if digitSum == target : 
      comboSum.append(checkno); 
     checkno = checkno + 1; 
    sumArray.append(len(comboSum)); 
    target = target + 1; 
    print (sumArray); 

findSum(); 

然而,當我把這種通過python解釋,它返回36個「0」的數組。我不太清楚爲什麼會出現這種情況,每當我增加目標,然後循環播放。

有誰知道這是爲什麼?

謝謝!

+1

請不要用分號結束Python中的行。 – poke

回答

2

在您增加target和循環後,您不會將checkno重設爲1000

目標所以第一次迭代中,你得到正確的答案0第二次迭代,其中target1,你checkno已經是10000,所以內循環將不會執行。

您需要將外部循環內的checknocomboSum的初始化。

+0

Oooh ...感謝您的幫助! – ForceFieldsForDoors

1

您可以通過for variable in range()取代你while循環,如:

def findSum(): 
    # target = 0 
    # checkno = 1000 
    # comboSum = [] 
    sumArray = [] 
    for target in range(36): 
     comboSum = [] 
     for checkno in range(1000, 10000): 
      digitSum = int(str(checkno)[0]) +\ 
         int(str(checkno)[1]) +\ 
         int(str(checkno)[2]) +\ 
         int(str(checkno)[3]) 
      if digitSum == target: 
       comboSum.append(checkno) 
      # checkno = checkno + 1 
     sumArray.append(len(comboSum)) 
     # target = target + 1 

    print(sumArray) 

findSum() 

這將是做一個更Python的方式。

由於強調了一些其他意見:

  • 永遠不會結束用分號
  • 通常線試着堅持PEP8規則(空格和身邊例如運營商)
+0

仍需重置'comboSum' – SpoonMeiser

+0

正確,編輯:) – filaton

0

如果你只是想找到有多少四位數字總和到你的目標的計數,你可以簡單地使用divmod來獲得數字和總是總和數字的總和等於你的目標數字:

def sum_digits(n, target): 
    n, sm = divmod(n, 10) 
    while n and sm <= target: 
     n, rem = divmod(n, 10) 
     sm += rem 
    return sm == target 



def find_sum(targ): 
    for n in range(1000, 10000): 
     yield sum_digits(n, targ) 


print(sum(findSum(36))) 

您是從0-target這是錯誤的根據您的描述檢查,發現的,加起來就是一個特定的值你應該只檢查目標數量四位數字編號。