Reputation: 19
Define a function, time(x,y), that takes time in hours and minutes rounds it to the nearest 5 minutes and expresses it as a word/string.
For example:
time(7,5) returns "five after seven"
time(7,13) returns "quarter after seven"
time(7,9) returns "ten after seven"
time(7,20) returns "twenty after seven"
time(7,24) returns "twenty five after seven"
time(7,30) returns "half past seven"
time(7,36) returns "twenty five to eight"
time(7,38) returns "twenty to eight"
time(7,45) returns "quarter to eight"
time(7,50) returns "ten to eight"
time(7,56) returns "five to eight"
time(12,00) returns "noon"
time(18,20) returns "twenty after six"
time(23,45) returns "a quarter to midnight"
My plan to code this was to use an array for the hours and if statements and append the minutes. I started with my code but I'm having troubles making it work
def time(h):
words=["midnight","one","two","three","four","five","six","seven","eight","nine","ten","eleven","noon"]
for n in range(len(words)):
h = (words[n])
return h
When I simply run just this code, it give me 'noon' every time. I know I am doing something wrong, can someone please help my fix this and give me a start in the right direction for the minutes.
Thanks
Upvotes: 0
Views: 95
Reputation: 117856
I'm sure I might have missed a few edge cases, but you could use this general idea.
hours = ["midnight","one","two","three","four","five","six","seven","eight","nine","ten","eleven","noon","one","two","three","four","five","six","seven","eight","nine","ten","eleven"]
minutes = ["", "five", "ten", "quarter", "twenty", "twenty five", "half", "twenty five", "twenty", "quarter", "ten", "five"]
def time(h,m):
if m < 2 or m > 58:
return str(hours[h])
elif m <= 30:
return str(minutes[int(round(float(m)/5))]) + " past " + str(hours[h])
else:
return str([int(round(float(m)/5))]) + " to " + str(hours[h+1])
Testing
>>> time(7,5)
'five past seven'
>>> time(7,13)
'quarter past seven'
>>> time(12,15)
'quarter past noon'
>>> time(21,45)
'quarter to ten'
Upvotes: 1
Reputation: 7064
You're over writing h every time you run this your for loop. It will return noon because noon is the last n in your loop.
Upvotes: 0
Reputation: 14731
The logic in your loop for n in range(len(words)):
seems wrong. You're just looping each element and assign it to h
(and at last h
remains the last value which is "noon"
).
Something like this would be a good start:
def time(h):
words = [
"midnight", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "noon"]
return words[h]
Or keep using the loop of yours (not recommended):
def time(h):
words = [
"midnight", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "noon"]
ret = None
for i in range(len(words)):
if i == h:
ret = words[i]
return ret
Upvotes: 2