I have no idea why when i run my code it returns wrong value.
JavaScript
x
26
26
1
from __future__ import annotations
2
3
4
class Duration:
5
6
def __init__(self):
7
self.hours = 0
8
self.days = 0
9
self.weeks = 0
10
11
def extendBy(self, hr: int) -> None: # there is a problem
12
print({self.weeks}, {self.days}, {self.hours})
13
if hr + self.hours < 24:
14
self.hours = hr
15
if hr + self.hours > 23:
16
self.hours = ((hr + self.hours) % 24)
17
self.days += int((hr - self.hours) // 24)
18
if self.days > 6:
19
if self.days % 7 == 0:
20
self.weeks = int(self.days // 7)
21
self.days = 0
22
else:
23
self.days = self.days % 7
24
self.weeks = int(self.days // 7)
25
print({self.weeks}, {self.days}, {self.hours})
26
These are the assertions that I use to test my code
JavaScript
1
8
1
a = Duration()
2
a.extendBy(25)
3
assert (a.weeks == 0 and a.days == 1 and a.hours == 1)
4
a.extendBy(24)
5
assert (a.weeks == 0 and a.days == 2 and a.hours == 1)
6
a.extendBy(7*24)
7
assert (a.weeks == 1 and a.days == 2 and a.hours == 1)
8
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:
JavaScript
1
26
26
1
class Duration:
2
3
def __init__(self):
4
self.hours = 0
5
self.days = 0
6
self.weeks = 0
7
8
def extendBy(self, hr):
9
if hr + self.hours < 24:
10
self.hours += hr
11
if hr + self.hours > 23:
12
self.days += (hr + self.hours) // 24
13
self.hours = (hr + self.hours) % 24
14
if self.days > 6:
15
self.weeks += self.days // 7
16
self.days = self.days % 7
17
print(self.weeks, self.days, self.hours)
18
19
a = Duration()
20
a.extendBy(25)
21
assert (a.weeks == 0 and a.days == 1 and a.hours == 1)
22
a.extendBy(24)
23
assert (a.weeks == 0 and a.days == 2 and a.hours == 1)
24
a.extendBy(7*24)
25
assert (a.weeks == 1 and a.days == 2 and a.hours == 1)
26
But something like this can be written in much simpler code using divmod
, try to see if you can figure it out.