2017-10-28 9 views
-1

リストからすべての数字を集計する関数を作成しようとしています。 7、私のコードであり、ここでは7の後に合計し続け:リスト内の6から7以外の数字の合計

def sum67(nums): 
    i = 0 
    sum = 0 
    while i < len(nums): 
     k = 0 
     if nums[i] != 0: 
     sum += nums[i] 
     i += 1 
     if nums[i] == 6: 
     for j in range(i + 1, len(nums)): 
      if nums[j] != 7: 
       k += 1 
      if nums[j] == 7: 
       k += 2 
       i += k 

テストケース6と7を含むまでアップ及び進行番号は他の数が合計に追加されている間無視され、後の数であることを示し7も加算されますが、何らかの理由で6が合計されなかった後の最初の7の後に7があります - これは私が望むものではなく、なぜ起こっているのかわかりません。助言がありますか?

テストケースの結果:

[1, 2, 2 Expected: 5. My result: 5 (OK) 

[1, 2, 2, 6, 99, 99, 7] Expected: 5. My result: 5 (OK) 
[1, 1, 6, 7, 2] Expected: 4 My result: 4 (Chill)  
[1, 6, 2, 2, 7, 1, 6, 99, 99, 7] Expected: 2 My result: 1 (Not chill)  
[1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7] Expected: 2 My result: 1 (Not chill) 
[2, 7, 6, 2, 6, 7, 2, 7] Expected: 18 My result: 9 (Not chill) 

`

答えて

0

投稿コードが完全に破壊されます。 たとえば、6がないリストの場合、 iは、最後の要素の条件がnums[i] == 6に達するとリストの範囲外になります。

ループ内の条件を完全に再考する必要があります。 ここではうまくいくアプローチがあります。 現在の番号が6の場合は、 をスキップし、合計に加算せずに7が表示されるまでスキップします。 それ以外の場合は合計に加算します。 これら2つのアクションのいずれかを実行した後(数字をスキップするか、または合計に加算する)、 のインクリメントi。ここで

def sum67(nums): 
    i = 0 
    total = 0 
    while i < len(nums): 
     if nums[i] == 6: 
      for i in range(i + 1, len(nums)): 
       if nums[i] == 7: 
        break 
     else: 
      total += nums[i] 

     i += 1 

    return total 
1
def sum67(nums): 
    # flag to know if we are summing 
    active = True 
    tot = 0 
    for n in nums: 
     # if we hit a 6 -> deactivate summing 
     if n == 6: 
      active = False 
     if active: 
      tot += n 
     # if we hit a seven -> reactivate summing 
     if n == 7 and not active: 
      active = True 
    return tot 
+1

正しいテストは 'のn == 6'なく' nが6'あります。それは小さな整数のために働く実装依存の詳細です。 – VPfB

+0

ありがとう、変更されました – user1620443

0

Pythonの新しい技術を習得するための中間の代替です:原則として

import itertools as it 


def span_sum(iterable, start=6, end=7): 
    """Return the sum of values found between start and end integers.""" 
    iterable = iter(iterable) 
    flag = [True] 
    result = [] 

    while flag: 
     result.extend(list(it.takewhile(lambda x: x!=start, iterable))) 
     flag = list(it.dropwhile(lambda x: x!=end, iterable)) 
     iterable = iter(flag) 
     next(iterable, []) 
    return sum(result) 

# Tests 
f = span_sum 
assert f([1, 2, 2]) == 5 
assert f([1, 2, 2, 6, 99, 99, 7]) == 5 
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2 
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2 
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18 

、この機能はあなたの条件を満たしてresultに値を収集し、入力をフィルタリングし、残りの部分を削除します、合計が戻されます。

関連する問題