Home > Software engineering >  Change iteration rate on itertools
Change iteration rate on itertools

Time:04-30

I have this iteration count using iter tools:

for i in itertools.count(start=2**68):

And I want it to bump up an exponent every time (68,69,70,71,...). Is there support for this in itertools? I have looked at the step option on the itertools documentation, but don't see any way to change by exponential type only float, integer.

CodePudding user response:

There is not a function specially made for that, but it's very easy to make what you want from basic components:

for i in map(lambda i: 2**i, itertools.count(start=68)):

Incidentally, one of the comments says map(lambda...) is an antipattern, and should instead be replaced with generator expressions. Here is how to do in case you wonder.

for i in (2**i for i in itertools.count(start=68)):

CodePudding user response:

Use itertools.count for the exponent, and do the exponentiation separately:

for exponent in itertools.count(start=68):
    i = 2 ** exponent
    print(i)

CodePudding user response:

To piggyback on the great answers by Barmar and Blackbeans, map may be used without lambda to achieve a solution.

import itertools
import functools
import math
pow_base2 = functools.partial(math.pow, 2)
for i in map(pow_base2, itertools.count(start=68)):
    print(i)

Or if you don't want to deal with floatS (thanks Kelly Bundy for the suggestion).

import itertools
import functools
pow_base2 = functools.partial(pow, 2)
for i in map(pow_base2, itertools.count(start=68)):
    print(i)
  • Related