There's probably already something like this in collections, but I wanted to write one, so came up with this.
I found it useful for a test case.
to use, instantiate class NumberGenerator like myctr = NumberGenerator(12, 8).numgen
now each time you call myctr() it returns a number starting at 12, and increments by 8
of course you can do the sane thing with range, if in a loop, this one does not require the loop.
I found it useful for a test case.
to use, instantiate class NumberGenerator like myctr = NumberGenerator(12, 8).numgen
now each time you call myctr() it returns a number starting at 12, and increments by 8
of course you can do the sane thing with range, if in a loop, this one does not require the loop.
class NumberGenerator: def __init__(self, start=0, increment=1): self.start = start self.increment = increment self.current_num = start def numgen(self): retval = self.current_num self.current_num += self.increment return retval def testit(): # test1 create a counter1 counts starting at 15 incrementing by 2 c1 = NumberGenerator(15, 2).numgen for x in range(10): print(f'c1: {c1()}') print() # test2 create another counter2 starts at 25 decrementing by -3 c2 = NumberGenerator(25, -3).numgen for x in range(10): print(f'c2: {c2()}') # test 3 one more time for each counter print(f'\nc1 again: {c1()}') print(f'c2 again: {c2()}\n') if __name__ == '__main__': testit()output:
Output:c1: 15
c1: 17
c1: 19
c1: 21
c1: 23
c1: 25
c1: 27
c1: 29
c1: 31
c1: 33
c2: 25
c2: 22
c2: 19
c2: 16
c2: 13
c2: 10
c2: 7
c2: 4
c2: 1
c2: -2
c1 again: 35
c2 again: -5