Categories
Coderbyte Data Structures and Algorithms Python String manipulation

[Coderbyte] – Time Convert [Easy]

The Time Convert challenge is the challenge I am going to explain in this article. The description below is taken straight from the Coderbyte website:

Have the function TimeConvert(num) take the num parameter being passed and return the number of hours and minutes the parameter converts to (ie. if num = 63 then the output should be 1:3). Separate the number of hours and minutes with a colon. 

The first step is to find out the hour from the num parameter. The hour can be found by dividing the num parameter by 60, which represents the number of minutes in an hour. However, in Python, there is a thing called floor division – the result of the division is rounded to the next smallest whole number, leaving out the remainder. E.g. 10//4 returns 2, whereas 10/4 returns 2.5. The line below does just that, it extracts the hour.

hour = num // 60

Once the hour is found, the next logical step is to find the minutes. The minutes are found by using the modulo (%) operator. The modulo operator returns the remainder of the division. E.g. 63 % 60 returns 3. Thus, the variable minutes from below extracts and stores the number of minutes from the num parameter.

minutes = num % 60

The last thing to do is to put the hours and minutes together. That can be done in different ways. In this case, I have decided to use the .format() method. The .format() method is a useful method, so it is worth a read about it here.

time = "{}:{}".format(hour, minutes)

Another alternative to the above code is:

time = str(hour) + ':' + str(minutes)

The challenge is solved. The full solution put together, can be seen below:

def TimeConvert(num): 
    # Floor division - division that results into whole number adjusted to the left in the number line
    hour = num // 60
    
    # Modulus - remainder of the division of left operand by the right
    minutes = num % 60
    
    # put the hour and minutes together
    time = "{}:{}".format(hour, minutes)
    
    return (time)

Leave a Reply

Your email address will not be published. Required fields are marked *