Just for an alternative, how about generalizing an iteration / increment operation to a lambda function so that you can do something like this:
for i in seq(1, 9, lambda x: x*2): print i ... 1 2 4 8
Where seq is defined below:
#!/bin/python from timeit import timeit def seq(a, b, f): x = a; while x < b: yield x x = f(x) def testSeq(): l = tuple(seq(1, 100000000, lambda x: x*2)) #print l def testGen(): l = tuple((2**x for x in range(27))) #print l testSeq(); testGen(); print "seq", timeit('testSeq()', 'from __main__ import testSeq', number = 1000000) print "gen", timeit('testGen()', 'from __main__ import testGen', number = 1000000)
The difference in performance is not much:
seq 7.98655080795 gen 6.19856786728
[EDIT]
Support reverse iteration and default argument ...
def seq(a, b, f = None): x = a; if b > a: if f == None: f = lambda x: x+1 while x < b: yield x x = f(x) else: if f == None: f = lambda x: x-1 while x > b: yield x x = f(x) for i in seq(8, 0, lambda x: x/2): print i
Note. This behaves differently to range / xrange , in which the direction test < / > is selected by the iterator icon, and not the difference between the start and end values.
jozxyqk Nov 25 '13 at 10:01 2013-11-25 10:01
source share