Splitting a string into some math gives a strange result, in Python

So, I admit that this is homework, but I do not ask you all to do it for me, I'm just looking for guidance. We need to make a Python program to accept the time in the format Hours: Minutes (2:30) on one line and print the time in minutes. (i.e. 2 hours and 30 minutes = 150 minutes).

I still need to work out some restrictions for entering a string:

  • Be sure to use only numbers and a colon
  • Make sure it can only accept five characters (##: ##)
  • Make sure the middle character is a colon (i.e. the numbers are in the correct order)
  • and make sure that if a time such as 4:35 was entered, zero will be added automatically automatically

I will work on this later - for now, I decided to work on the math that I would get from input.

It was wise for me to cut the string into two parts: hours and minutes. Then I multiplied the number of hours by 60 and added them to the pre-existing minutes to get the total number of minutes. However, right now, during, for example, 02:45, a minute quantity of 0202020202020202020202020202020202020202020202020202020202020202020202020202020205 is issued.

Any idea what might be wrong here? To be clear, this is homework, and I want to deal with input restrictions myself, I just need help in promoting this mathematical problem.

#Henry Quinn - Python Advanced 4.0 Hours and Minutes import re print "This program takes an input of time in hours and minutes and outputs the amount of minutes." count = 0 #I still need to work out while loop #Supposed to make sure that a time is entered correctly, or error out while (count <1): time = raw_input("Please enter the duration of time (ex: 2:15 or 12:30): ") if not re.match("^[0-9, :]*$", time): print "Sorry, you're only allowed to use the numbers 0-9." elif len(time) > 5: print "Sorry, only five characters max allowed." #MAKE THIS CHECK FOR A COLON #elif #elif else: count = count + 1 #If time = 12:45, hours should be equal to 12, and minutes should be equal to 45 hours = time[:2] minutes = time[3:] #Should convert hours to minutes newhours = hours * 60 #Should make total amount of minutes totalminutes = newhours + minutes print "The total amount of elapsed minutes is %s" % (totalminutes) raw_input("Please press Enter to terminate the program.") 
+4
source share
4 answers

Right now, hours and minutes are string variables, not int. Thus, you cannot multiply them as a number.

Change lines 20 and 21 to

 hours = int(time[:2]) minutes = int(time[3:]) 

And 02:45 surrender should work. However, you will still encounter problems if you do not have this leading 0 (for example, if you add 2:45), so I can suggest that you break it into ":" instead, for example:

 hours = int(time.split(":")[0]) minutes = int(time.split(":")[1]) 
+5
source

You multiply a string with an integer.

 >>> st = '20' >>> st*3 '202020' >>> int(st)*3 60 >>> 

Enter an int value.

So change this

 minutes = time[3:] newhours = hours * 60 

to

  minutes = int(time[3:]) newhours = int(hours) * 60 
+3
source

Since this is homework, here is the solution - if you find out how it works, I guarantee that you will learn something new;)

 tre = re.compile("([0-2]?[0-9]):([0-5][0-9])") h,m = ((int(_) for _ in tre.match("2:30").groups()) td = timedelta(hours=h, minutes=m) print(td.total_seconds() / 60) 
+1
source

The second and fourth requirements contradict each other. Either you accept only strings of 5 characters, or you also allow #:## (4 characters).

 import re def minutes(timestr): """Return number of minutes in timestr that must be either ##:## or #:##.""" m = re.match(r"(\d?\d):(\d\d)$", timestr) if m is None: raise ValueError("Invalid timestr: %r" % (timestr,)) h, m = map(int, m.groups()) return 60*h + m 

If you allow spaces inside the forms timestr and ##:# , #:# etc., then:

 def minutes2(timestr): h, m = map(int, timestr.partition(':')[::2]) return 60*h + m 

If you want to limit hours to 0..23 and minutes to 0..59, then:

 import time def minutes3(timestr): t = time.strptime(timestr, "%H:%M") return 60*t.tm_hour + t.tm_min 

Example

 minutes ('12:11') -> 731 minutes2('12:11') -> 731 minutes3('12:11') -> 731 minutes (' 12:11') -> error: Invalid timestr: ' 12:11' minutes2(' 12:11') -> 731 minutes3(' 12:11') -> error: time data ' 12:11' does not match format '%H:%M' minutes ('12:11 ') -> error: Invalid timestr: '12:11 ' minutes2('12:11 ') -> 731 minutes3('12:11 ') -> error: unconverted data remains: minutes ('3:45') -> 225 minutes2('3:45') -> 225 minutes3('3:45') -> 225 minutes ('03:45') -> 225 minutes2('03:45') -> 225 minutes3('03:45') -> 225 minutes ('13:4') -> error: Invalid timestr: '13:4' minutes2('13:4') -> 784 minutes3('13:4') -> 784 minutes ('13:04') -> 784 minutes2('13:04') -> 784 minutes3('13:04') -> 784 minutes ('24:00') -> 1440 minutes2('24:00') -> 1440 minutes3('24:00') -> error: time data '24:00' does not match format '%H:%M' minutes ('11:60') -> 720 minutes2('11:60') -> 720 minutes3('11:60') -> error: unconverted data remains: 0 
+1
source

Source: https://habr.com/ru/post/1396255/


All Articles