2015-10-10 33 views
-2

我目前正在嘗試在Python中編寫一個函數,該函數將採用subsetSum(lst,num)並遍歷列表lst,如果有三個值合計爲num,則返回True。如果列表lst中沒有三個值合計爲number num,則函數返回False。以下是我迄今爲止(我剛開始學習Python,所以請不要苛刻!!):Python subsetSum函數

def subsetSum(lst, n): 

    ''' checks to see if 3 values in lst add up to n and returns True, otherwise false''' 

    if n == 0 or n < 1: 
     return False 
    elif len(lst) < 3: 
     return False 

    for i in range(len(lst)): 
     if lst[0] == n: 
      return True 
    return False 

不知怎的,我需要通過這個列表LST進行迭代,找到3個值加起來到n。

+0

向我們顯示您的嘗試,我們將幫助您改進它。 –

+0

這三個數字是否必須在列表中順序出現? – martineau

+0

@martineau不,數字不必在列表中順序出現。 –

回答

0

這是使用嵌套循環的溶液中。我只是剛剛學習語言,所以它可能不是慣用的蟒蛇,但它的工作原理:

def subset_sum(lst, n): 
    for i in range(len(lst)): 
     for j in range(i + 1, len(lst)): 
      for k in range(j + 1, len(lst)): 
       if lst[i] + lst[j] + lst[k] == n: 
        return True 
    return False  
+0

這個完美的作品!我不敢相信我沒有想到嵌​​套循環。 –

+0

很高興我能幫到你。 –

0

itertools.combinations使用和any

>>> any(sum(e)== 30 for e in combinations(range(1,22), 3)) 
True 
>>> any(sum(e)== 300 for e in combinations(range(1,22), 3)) 
False