python - Incrementing in a for loop -


so issue not incrementing correctly... tried uses int "step" + 1 every time loop ran doesn't anything. why that? when print(step) adds 337. not go full 1000 had thought asked too. how do correctly?

lockers = []  step = 3  locker = 0  while len(lockers) <= 1000:      lockers.append(1)  in range(0, len(lockers)):      lockers[i] = 0  in range(0, len(lockers), 2):      lockers[i] = 1  in range(0, len(lockers), step):      if lockers[i] == 0:           lockers [i] = 1      else:           lockers[i] = 0       step += 1   print(lockers) 

range gives iterable object:

>>> range(10,20 , 2) range(10, 20, 2) >>> list(range(10,20 , 2)) [10, 12, 14, 16, 18] 

the values in decided call returns, , aren't re-evaluated each time around loop. step goes 337 because incrementing once each element in object range(0, 1000, 3), has 334 items, not 1000:

>>> len(range(0,1000,3)) 334 

to works range advances step, need write own generator:

def advancing_range(start, stop, step):     ''' range(start, stop, step) except step incremented          between each value      '''     while start < stop:         yield start         start += step         step += 1 

you can for in advancing_range(0, 1000, 3): , work intend.

but strange thing want do. judging variable names, guess you're coding locker problem, says:

a new high school has been completed. there 1,000 lockers in school , have been numbered 1 through 1,000. during recess (remember fictional problem), students decide try experiment. when recess on each student walk school 1 @ time. first student open of locker doors. second student close of locker doors numbers. third student change of locker doors multiples of 3 (change means closing lockers open, , opening lockers closed.) fourth student change position of locker doors numbered multiples of 4 , on. after 1,000 students have entered school, locker doors open, , why?

but advancing range logic says more "the first student opens first locker, second opens second locker after that, third student opens third locker after ...". want affect multiple lockers each time, further spaced out. essentially, want copy , paste first 2 loops 998 times 1 higher step each time. of course, can better copy , paste, , seems want 2 nested loops, outer 1 advances step inner 1 uses. this:

for step in range(1, len(lockers)):     in range(step, len(lockers), step): 

simplifying other logic using booleans instead of 1 , 0, whole program looks this:

lockers = [true] * 1000  step in range(1, len(lockers)):     in range(step, len(lockers), step):         lockers[i] = not lockers[i]  print(sum(lockers)) 

it prints number of open lockers 969.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -