oop - Building a python counter with rollover -
I need to create a message counter object - not to be confused with the counter class of Python. The specification calls for a counter that starts from 0, then increments to 1 until it becomes 4294967295, at which point it should move backwards to 1.
I have applied a class to do this, but this is just a naïve attitude, is there a better way of achieving this goal?
class messagecountor (): def __init __ (self): self.value = 0 def increment (self): if self.value & lt; 4294967295: self.value + = 1 other: self.reset () Def reset (): self.value = 1
As an option for OO, you can create a creative task that creates numbers in sequence, forever. There are a number of ways to do this. In the descending order of size and simplicity:
def count_loop (upper_limit): while true: I (upper_limit) for the range: produce i gen = count_loop (42 94967295)
i itertools GEN = (itertools.count for _ in I) category (42 9 497272) for gene = (For the I category of I (int, 1) for i category (42 9 4967295))
You will then reclaim your values by doing next (gen)
.
& gt; & Gt; & Gt; Next (GN) 0 >> gt; & Gt; Next (GN) 1 & gt; & Gt; & Gt; Next (GN) 2> gt; & Gt; & Gt; Next (genes) 3
(Note: Python 2.7 users should use the category
instead of xrange
. It can work for maximum value of 2 ^ 31)
Comments
Post a Comment