【发布时间】:2018-08-31 22:11:29
【问题描述】:
所以我有一个任务,我得到一个包含呼叫(呼叫持续时间,呼叫号码)的字符串,任务是计算总持续时间。 有一些额外的检查: 如果持续时间 > 5 分钟,则仅计算分钟(150 美分/分钟) 对于持续时间最长的电话号码,通话是免费的,因此是 0 美分。
我写了代码,正确答案必须是 900。但是当我运行代码时,结果总是不同。有时是0,有时是900,是什么原因?
import re
string = '''
00:01:07,400-234-090\n
00:05:01,701-080-080\n
00:05:00,400-234-090\n
'''
pattern = r'(?P<duration>[\d]{2}:[\d]{2}:[\d]{2}),(?P<phone>[\d]{3}-[\d]{3}-[\d]{3})'
duration = {}
for s in string.split('\n'):
match = re.fullmatch(pattern, s)
if match:
hour, minutes, sec = match.group('duration').split(':')
sec = int(sec)
minutes = int(minutes)
hour = int(hour) * (minutes * sec)
if minutes < 5:
total = (hour + (minutes * 60) + sec) * 3
print(s + ' - matched! Total seconds:' + str(total))
if not match.group('phone') in duration:
duration[match.group('phone')] = total
else:
duration[match.group('phone')] += total
elif minutes >= 5 and sec == 0:
total = (minutes * 150)
print(s + ' - matched! Total seconds:' + str(total))
if not match.group('phone') in duration:
duration[match.group('phone')] = total
else:
duration[match.group('phone')] += total
elif minutes >= 5 and sec >= 1:
total = (minutes * 150) + 150
print(s + ' - matched! Total seconds:' + str(total))
if not match.group('phone') in duration:
duration[match.group('phone')] = total
else:
duration[match.group('phone')] += total
for k, v in duration.items():
if v == max(duration.values()):
duration[k] = 0
print(sum(duration.values()))
【问题讨论】:
-
无论我在哪里运行,每次运行它都会得到相同的结果。有三个“匹配”!分别为 201、900、750 秒的行,最终输出为 0。
-
@abarnert 它必须是 900,因为 2 个数字的总数是 900 和 950。950 是一个更大的数字,所以它等于 0。为什么会这样?它必须是 900
-
啊,您可能正在运行字典(带有字符串键)具有显式随机顺序的 Python 版本,例如 3.5,而我正在运行字典主要插入顺序的版本, 3.7.这就是为什么你每次都会得到不同的结果,而我总是得到相同的结果。当你得到 900 时,这基本上是纯粹的运气 - 字符串碰巧被哈希随机化成一个顺序,使
max(duration.values())将正确的条目归零。
标签: python