What is wrong in this example code?
Nathan Hilterbrand
nhilterbrand at gmail.com
Thu Nov 12 19:24:23 EST 2015
On Thu, Nov 12, 2015 at 6:59 PM, Larry Hudson via Python-list <
python-list at python.org> wrote:
Nothing to do with your original question, just a trivial suggestion which
> you are free to ignore. You can shorten this tick() method by using the
> divmod() function. It does a division and returns both the quotient AND
> the remainder. IOW, given divmod(x, y) it returns the tuple (x/y, x%y).
> It is a very useful function. Try this:
>
> def tick(self):
> xtra, self._seconds = divmod(self._seconds + 1, 60)
> xtra, self._minutes = divmod(self._minutes + xtra, 60)
> self._hours += xtra
>
> Explanation: (to shorten this, I'm leaving off the leading "self._" from
> the actual code.)
> The first divmod() sets xtra = (seconds+1) / 60, which is the 'overflow'
> if any, from the division by 60, and seconds is the updated seconds limited
> to 0-59 (the result of (seconds+1) % 60). The second divmod() does the
> same thing to update minutes (if xtra != 0) and xtra is set to the
> 'overflow' from that division, which is then added to hours.
>
> More confusing perhaps, but definitely shorter.
> As I said above, use it if you want or ignore it if it's too confusing.
>
> -=- Larry -=-
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
Beat me to the punch. I was about to suggest something similar, but I
thought that since one using this class would probably be "tick()-ing" more
than "str()-ing", It might also be better to store the value in seconds,
and convert to HH:MM:SS upon stringification; again using divmod:
class Clock(object):
def __init__(self,hours=0,minutes=0,seconds=0):
self.set(hours,minutes,seconds)
def tick(self):
self.__secs+=1
def set(self,hours, minutes, seconds):
self.__secs = seconds + (minutes*60) + (hours*60*60)
def __str__(self):
rest, seconds = divmod(self.__secs, 60)
hours, minutes = divmod(rest, 60)
return "%02d:%02d:%02d" % (hours, minutes, seconds)
def display(self):
print(str(self))
if __name__ == "__main__":
x = Clock()
print("Default construction, no parameters, Before ticks: {}".format(x))
for i in range(10000):
x.tick()
print("After ticks: {}".format(x))
x = Clock(hours=2, minutes=20, seconds=5)
print("\nConstructor with hours=2, minutes=20, seconds=5: {}".format(x))
print("Test of display() method: ",end=' ')
x.display()
This is my first post here, and I am a Python n00b (coming from that
four-letter word language "p***"), so if I broke some top/bottom posting or
formatting rules, I apologize, and would appreciate any posting pointers
Nathan H.
More information about the Python-list
mailing list