に達するか超えないよう
def days_to_reach_n_steps(step_records, n):
"""DOCSTRING"""
total_steps = 0
counter = 0
while total_steps < n:
total_steps = total_steps + step_records[counter][1]
counter = counter + 1
return(counter)
私は、この特定の例では、と私の機能をテストしていものの例は、None
を返す必要がありますそれは思われます私には最も簡単な解決策はfor
ループです。基本的には繰り返しが必要です。あなたはまた、一日を追跡するためにenumerate
を使用することができます。その累積和が正方形であると、私は一連のステップとして、奇数番号を選択した
sample_steps = [("2010-01-1", 1),
("2010-01-2", 3),
("2010-01-3", 5),
("2010-01-4", 7),
("2010-01-5", 9),
("2010-01-6", 11)]
def days_to_reach_n_steps(step_records, n):
total_steps = 0
for counter, (date, steps) in enumerate(step_records, 1):
total_steps += steps
if total_steps >= n:
return counter, date
(それが簡単に目でチェックすることができます):
days_to_reach_n_steps
は一つだけ
return
文が
0 steps in 1 days (arrived at 2010-01-1)
1 steps in 1 days (arrived at 2010-01-1)
2 steps in 2 days (arrived at 2010-01-2)
3 steps in 2 days (arrived at 2010-01-2)
4 steps in 2 days (arrived at 2010-01-2)
5 steps in 3 days (arrived at 2010-01-3)
8 steps in 3 days (arrived at 2010-01-3)
9 steps in 3 days (arrived at 2010-01-3)
10 steps in 4 days (arrived at 2010-01-4)
15 steps in 4 days (arrived at 2010-01-4)
16 steps in 4 days (arrived at 2010-01-4)
17 steps in 5 days (arrived at 2010-01-5)
24 steps in 5 days (arrived at 2010-01-5)
25 steps in 5 days (arrived at 2010-01-5)
26 steps in 6 days (arrived at 2010-01-6)
35 steps in 6 days (arrived at 2010-01-6)
36 steps in 6 days (arrived at 2010-01-6)
37 was unreached
。なお、それでもに管理します。
for boundary in range(1, 7):
for steps in range(boundary ** 2 - 1, boundary ** 2 + 2):
result = days_to_reach_n_steps(sample_steps, steps)
if result:
days, date = result
print("{} steps in {} days (arrived at {})".format(steps, days, date))
else:
print("{} was unreached".format(steps))
これは、これを返します。None
(37
)。暗黙的に何も返さない関数がNone
を返すからです。しかし、これは非常にあなたが0の例外になりたい場合は、私はこれを行うことをお勧めしたい0のためにあなたの仕様に一致していません:
for counter, (date, steps) in enumerate([("start", 0)] + step_records):
答えの最初の行は
0 steps in 0 days (arrived at start)
これに変更されます残りのアルゴリズムは維持されるため、エッジケースをプログラムする必要はありません。それはwhileループをしなければならない場合
、あなたは少し冗談これにforループ書き換えることができます:
def days_to_reach_n_steps(step_records, n):
total_steps = 0
counter = 0
step_records = [("start", 0)] + step_records
while counter < len(step_records):
date, steps = step_records[counter]
total_steps += steps
if total_steps >= n:
return counter, date
counter += 1
これはまさにループアプローチのための2回目と同じように動作します($ diff <(python while.py) <(python code.py)
終了をきれいに) 。
step_records
に再割り当てを削除し、counter + 1
を返し、forループの最初の繰り返しのようになり、それを適合させます。
これは実際にはwhileループの良いアプリケーションではないことに注意してください - おそらく、whileループで練習することを意図していますが、私は醜いコードを強制することを本当に認めていません - Pythonは既にリストを反復するための簡単なイディオム指数を維持する。 the Zen of Pythonを参照してください。
が
あなたは 'step_records'がどのように見えるかのサンプルを提供することができます(なぜそれがタプルのリストです?)、あなたの予想される出力はあなたがこれまでに得ているものとは何ですか? –
私の質問を、私が関数を呼び出しているもののサンプルで編集しました。 'step_records'の日付部分を' n 'に達した日付を返すように修正した後で使用しますが、この部分を残しておきたいと思っていました。最初の部分を最初に考え出す。 –
「n」が0だった場合に返される日数/日数は何ですか? –