Python - Using index from tuple list, how to solve when index out of range only using while statement -


i made while loop :

  1. counts daily steps in list of tuple
  2. returns number of days taken aimed steps.
  3. must return none if total steps lower aimed steps.

this works fine until index range exceeds given list.

i've attempted various ways using if statement below couldn't make work.. found works when change index value > len(step_records) seems error when index value += 1 while loop.

* not allowed use statement.


step_records = [('2010-01-01',1),                 ('2010-01-02',2),                 ('2010-01-03',3)]  aim_steps = 7 total_steps = 0 index = 0 days = 0   if len(step_records) >= index:     while total_steps < aim_steps:         total_steps += step_records[index][1]         index += 1         days += 1         print(days) else:     days = none     print(days)     

results in

traceback (most recent call last):   file "/users/lowden/untitled-3.py", line 13, in <module>     total_steps += step_records[index][1] indexerror: list index out of range 

well, problem check whether index greater len(step_records) once. enter while loop, has no checks whether has index exceeded len(step_records). is, once you're inside if statement, no more len(step_records) >= index checks being done, , after 3 iterations error (when index becomes 3, whereas maximum index of step_records 2).

you try this:

...  while len(step_records) > index:     if total_steps < aim_steps:         total_steps += step_records[index][1]         days += 1         index += 1 ... 

with code, each iteration you'd check whether index still less total size of list. if exceed aim_steps, iterate until index larger len(step_records). or add else condition break inside it, break out of loop immediately.

unlike of other solutions, should not hang when different step values (i.e., 1) inputted.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -