4

ですから、これは宿題であることを認めますが、私はあなた方全員にそれをしてくれるように頼んでいるのではなく、ただいくつかのガイダンスを探しています。時間を1つの文字列でHours:Minutes(2:30)形式で受け入れ、時間を分単位で出力するPythonプログラムを作成する必要があります。(つまり、2時間30分= 150分)

文字列入力のいくつかの制限を解決する必要があります。

  1. 数字とコロンのみを使用するようにしてください
  2. 5文字のみを受け入れることができることを確認してください(##:##)
  3. 真ん中の文字がコロンであることを確認してください(つまり、数字が正しい順序になっている)
  4. そして、4:35のような時間が入力された場合、ゼロが自動的に前に追加されることを確認してください

これについては後で作業します—今のところ、入力から得られる数学に取り組むことにしました。

文字列を時間と分という2つの部分にスライスすることは私にとって理にかなっています。次に、時間数に60を掛け、それらを既存の分に加算して、合計分数を取得しました。ただし、現在、02:45のような時間に入ると、02020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020

ここで何がうまくいかないのでしょうか?明確にするために、これは宿題であり、入力の制限を自分で解決したいので、この数学の問題を乗り越える手助けが必要です。

#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

4 に答える 4

5

現在、時間と分は整数ではなく文字列変数です。したがって、数値のように乗算することはできません。

20 行目と 21 行目を次のように変更します。

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

そして、02:45 を入れるとうまくいくはずです。ただし、先頭に 0 がない場合 (2:45 を挿入した場合など) にも問題が発生するため、次のように ":" で区切ることをお勧めします。

hours = int(time.split(":")[0])
minutes = int(time.split(":")[1])
于 2012-02-13T18:03:14.273 に答える
3

文字列に整数を掛けています。

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

に型キャストしintます。

だから、これを変更してください

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

 minutes = int(time[3:])
 newhours = int(hours) * 60
于 2012-02-13T18:03:46.177 に答える
1

これは宿題なので、ここに解決策があります - それがどのように機能するかを理解すれば、私はあなたが何か新しいことを学ぶことを保証します;)

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)
于 2012-02-13T18:14:50.923 に答える
1

2 番目と 4 番目の要件は互いに矛盾しています。5 文字の文字列のみを受け入れるか、それも許可します#:##(4 文字の形式)。

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

timestrand ##:##:#などのフォーム内にスペースを許可する場合:

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

時間を 0..23 に、分を 0..59 に制限したい場合:

import time

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

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
于 2012-02-13T18:43:39.523 に答える