這似乎是一個例子對我來說,最簡單的解決方案是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
我選擇了奇數的步驟順序作爲其累加的平方(使得它更容易用肉眼檢查):
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))
這將返回此:
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
注意days_to_reach_n_steps
只有一個return
聲明,但仍設法return
None
爲37
。這是因爲隱含的函數不返回任何東西會返回None
。然而,這並不完全匹配您的規範0我建議這樣做,如果你想0是例外:
for counter, (date, steps) in enumerate([("start", 0)] + step_records):
答案的第一行會變成
0 steps in 0 days (arrived at start)
這保持算法的其餘部分,所以你不需要編程邊界情況。
如果它是一個while循環,你可以稍微開玩笑改寫爲循環成這樣:
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
這工作完全一樣的for循環方法的第二次迭代($ diff <(python while.py) <(python code.py)
乾淨地退出) 。
爲了使其適應類似於for循環的第一次迭代,請將重新分配移除到step_records
並返回counter + 1
。
請注意,這不是一個真正的while循環的應用程序 - 也許其目的是通過while循環獲得練習,但我並不真的贊成強制醜陋的代碼 - Python已經有了用於遍歷列表的簡單成語並保持指數。見the Zen of Python。
你能提供什麼'step_records'看起來像一個樣本(爲什麼是一個元組列表,如果你只使用一個部分?),以及你期望的輸出與你到目前爲止得到的結果? –
用我正在調用函數的示例編輯我的問題。我將在修改函數後使用'step_records'的日期部分來返回'n'的日期,但我認爲最好不要將這部分留下,因爲我認爲我應該關注首先找出最初的部分。 –
如果'n'爲0,你會返回多少天/日期? –