Reputation: 605
I'm creating a function that receives the tenths of second (t) and returns a processed string (digital clock like).
Is there a better/easier/optimum way to do it?
Output format: A:BC.D (Minutes : Seconds . Tenths)
def format(t):
A = 0
B = 0
C = 0
D = t
if t >= 10:
C = t // 10
D = t % 10
if C >= 10:
B = C // 10
C = C % 10
if B >= 6:
A = B // 6
B = B % 6
return str(A) + ":" + str(B) + str(C) + "." + str(D)
Upvotes: 1
Views: 2499
Reputation: 86894
def format(t):
seconds, fractions = divmod(t, 10)
minutes, seconds = divmod(seconds, 60)
return "%d:%02d.%d" % (minutes, seconds, fractions)
example output:
>>> format(10)
'0:01.0'
>>> format(100)
'0:10.0'
>>> format(1000)
'1:40.0'
Upvotes: 1
Reputation: 500475
All those ifs
are completely unnecessary, and a few other things can be simplified:
def fmt(t):
tenths = t % 10
t //= 10
sec = t % 60
t //= 60
min = t
return '%d:%02d.%d' % (min, sec, tenths)
print(fmt(1234))
Upvotes: 3