Python在复杂方程中计算大量数据时遇到问题

时间:2016-09-28 03:45:55

标签: python complex-numbers canopy

我正在编写一些代码,允许用户输入秒数,并接收它产生的天数,小时数,分钟数和秒数。但是,如果我输入任何大于311039999的数字,则小时数将变为24+,而不是0。

现在我有一些编程的东西告诉用户如果超过前面提到的值,那么这个数字太大了,但是我想改变它以便它不再是问题了。

这是我的代码:

user_sec= int(input("How many seconds are there? "))
#When max value is minutes, displays number of minutes
tot_min_min = user_sec/60
#When max value is minutes, displays number of seconds
tot_min_sec = user_sec%60

#When max value is hours, displays number of hours
tot_hr_hr = user_sec/3600
#When max value is hours, displays number of minutes
tot_hr_min = tot_min_min%60
#When max value is hours, displays number of seconds
tot_hr_sec = user_sec%60

#When max value is days, displays number of days
tot_day_day = user_sec/86400
#When max value is days, displays number of hours
tot_day_hr = tot_hr_hr/3600
#When max value is days, displays number of minutes
tot_day_min = tot_hr_min%60
#When max value is days, displays number of seconds
tot_day_sec = user_sec%60

if user_sec >= 311040000:
    print 'Your number is too large to calculate.'
elif user_sec >= 60 and user_sec < 3600:
        print '{} seconds makes {} minute(s) and {} second(s).'.format(user_sec,tot_min_min,tot_min_sec)
elif user_sec >= 3600 and user_sec < 86400:
        print '{} seconds makes {} hour(s), {} minute(s) and {} second(s).'.format(user_sec,tot_hr_hr,tot_hr_min,tot_hr_sec)
elif user_sec >= 86400 and user_sec < 311040000:
        print '{} seconds makes {} days(s), {} hour(s), {} minute(s) and {} second(s).'.format(user_sec,tot_day_day,tot_day_hr,tot_day_min,tot_day_sec)
else:
    print 'There is/are {} second(s).'.format(user_sec)

我正在使用Canopy,如果这有帮助的话。简单的答案是值得赞赏的,因为我已经这样做了几个星期。

[编辑]以下是我的问题的一个例子。如果user_sec = 1000000000,则打印出“1000000000秒使得11574天,77小时,46分钟和40秒(秒)”。我不确定数学问题在哪里,但正确答案是“11574天, 1 小时,46分40秒。”

1 个答案:

答案 0 :(得分:2)

如果您不介意使用第三方模块,dateutil提供了一种简单的方法:

from dateutil.relativedelta import relativedelta

user_sec = int(input("How many seconds are there? "))
d = relativedelta(seconds=user_sec)
print(d)

如果您输入351080000

,则会输出以下内容
relativedelta(days=+4063, hours=+10, minutes=+13, seconds=+20)

从那里你可以打印出更友好的用户名字符串:

print('{0} seconds makes {1.days} days(s), {1.hours} hour(s), {1.minutes} minute(s) and {1.seconds} second(s).'.format(user_sec, d))

351080000 seconds makes 4063 days(s), 10 hour(s), 13 minute(s) and 20 second(s).

否则计算天数非常简单。小时,分钟和秒:

n = user_sec
days, n = divmod(n, 86400)
hours, n = divmod(n, 3600)
minutes, n = divmod(n, 60)
seconds = n

print('{} seconds makes {} days(s), {} hour(s), {} minute(s) and {} second(s).'.format(user_sec, days, hours, minutes, seconds))