Skip to content
Advertisement

Python: class and object

I have no idea why when i run my code it returns wrong value.

from __future__ import annotations


class Duration:

    def __init__(self):
        self.hours = 0
        self.days = 0
        self.weeks = 0

    def extendBy(self, hr: int) -> None:  # there is a problem
        print({self.weeks}, {self.days}, {self.hours})
        if hr + self.hours < 24:
            self.hours = hr
        if hr + self.hours > 23:
            self.hours = ((hr + self.hours) % 24)
            self.days += int((hr - self.hours) // 24)
        if self.days > 6:
            if self.days % 7 == 0:
                self.weeks = int(self.days // 7)
                self.days = 0
            else:
                self.days = self.days % 7
                self.weeks = int(self.days // 7)
        print({self.weeks}, {self.days}, {self.hours})

These are the assertions that I use to test my code

a = Duration()
a.extendBy(25)
assert (a.weeks == 0 and a.days == 1 and a.hours == 1)
a.extendBy(24)
assert (a.weeks == 0 and a.days == 2 and a.hours == 1)
a.extendBy(7*24)
assert (a.weeks == 1 and a.days == 2 and a.hours == 1)

when i print out my code i get a correct result for weeks and hours, buts for days I always get the wrong result. If anybody know could youplease help me.

Advertisement

Answer

I couldn’t figure out what your logic is when reading your code, so I rewrote some of the logic while still keeping the overall structure the same:

class Duration:

    def __init__(self):
        self.hours = 0
        self.days = 0
        self.weeks = 0

    def extendBy(self, hr):
        if hr + self.hours < 24:
            self.hours += hr
        if hr + self.hours > 23:
            self.days += (hr + self.hours) // 24
            self.hours = (hr + self.hours) % 24
        if self.days > 6:
            self.weeks += self.days // 7
            self.days = self.days % 7
        print(self.weeks, self.days, self.hours)

a = Duration()
a.extendBy(25)
assert (a.weeks == 0 and a.days == 1 and a.hours == 1)
a.extendBy(24)
assert (a.weeks == 0 and a.days == 2 and a.hours == 1)
a.extendBy(7*24)
assert (a.weeks == 1 and a.days == 2 and a.hours == 1)

But something like this can be written in much simpler code using divmod, try to see if you can figure it out.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement