Change iteration rate on itertools

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)):

Method 2

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

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

Method 3

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)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x