patternpythonMinor
Expressing current time with natural language
Viewed 0 times
expressingwithtimelanguagenaturalcurrent
Problem
def current_time():
'''Returns a tuple containing (hour, minute) for current local time.'''
import time
local_time = time.localtime(time.time())
return (local_time.tm_hour, local_time.tm_min)
(hour,minute) = current_time()
def ishtime(hour, minute):
import random
Starting_str = ['it is','its',"it's","Current time is"]
h_str = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']
mid_str = ['almost','nearly','roughly','maybe']
Ex = ['Exactly' , 'Perpectly' ,'']
m_str = ['ten','twenty','thirty','fourty','fifty']
End_str = ['in the morning','in the afternoon','in the evening','at night']
## - define random strings
Head = Starting_str[int(random.random()*4)]
Mid = mid_str[int(random.random()*4)]
Hour = h_str[(int(hour)-1)%12]
if round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
Rand_m_str = ''
else:
Rand_m_str = m_str[int((round(int(minute),-1)/10))-1]
## -define for final ex)its , it's , almost, one two three..
if int(hour)>=6 and int(hour)=13 and int(hour)=19 and int(hour)=0 and int(hour)<6:
Ending = End_str[3]
## - define 'ending str' ex) in the morning
if minute == 0 or minute == 00:
Result = "%s %s 'o clock %s" %(Head,Hour,Ending)
elif minute%10 == 0:
Result = "%s %s %s after %s %s" %(Head,Ex[int(random.random()*4)],Rand_m_str,Hour,Ending)
elif round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
Result = "%s %s %s%s %s" %(Head,Mid,Rand_m_str,Hour,Ending)
else:
Result = "%s %s %s minute after %s %s" %(Head,Mid,Rand_m_str,Hour,Ending)
return Result
print ishtime(hour,minute)I did this job.. how could i make it simpler?
Solution
Python supports double-ended inequalities:
I've changed 23 to 24 for consistency and rearranged the members of
I would expect noon and midnight to be handled as special cases.
End_str = ['at night', 'in the morning','in the afternoon','in the evening']
if 0 <= hour < 6:
Ending = End_str[0]
elif 6 <= hour < 13:
Ending = End_str[1]
elif 13 <= hour < 19:
Ending = End_str[2]
elif 19 <= hour < 24:
Ending = End_str[3]I've changed 23 to 24 for consistency and rearranged the members of
End_str. I don't see how hour should be anything other than an integer, so I've removed the casts.if minute == 0 or minute == 00 is redundant, since 00 is exactly the same as 0.I would expect noon and midnight to be handled as special cases.
Code Snippets
End_str = ['at night', 'in the morning','in the afternoon','in the evening']
if 0 <= hour < 6:
Ending = End_str[0]
elif 6 <= hour < 13:
Ending = End_str[1]
elif 13 <= hour < 19:
Ending = End_str[2]
elif 19 <= hour < 24:
Ending = End_str[3]Context
StackExchange Code Review Q#37522, answer score: 3
Revisions (0)
No revisions yet.