因此,我有一个任务,给我一个包含呼叫的字符串(呼叫持续时间,呼叫号码),并且任务是计算总持续时间。 还有一些额外的检查: 如果持续时间> 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()))
答案 0 :(得分:1)
问题是您在for循环中找到了dict值的最大值。
>>> duration
{'400-234-090': 951, '701-080-080': 900}
>>>
>>> for k, v in duration.items():
... if v == max(duration.values()):
... duration[k] = 0
...
>>> duration
{'400-234-090': 0, '701-080-080': 0}
>>>
>>> print(sum(duration.values()))
0
只需在循环外进行一次计算即可得到预期的答案。
>>> duration
{'400-234-090': 951, '701-080-080': 900}
>>>
>>> max_val = max(duration.values())
>>> for k, v in duration.items():
... if v == max_val:
... duration[k] = 0
...
>>> print(sum(duration.values()))
900
答案 1 :(得分:1)
您将获得随机结果,因为您正在重新计算字典循环中的最大值:不能保证键顺序在不同的运行中保持一致。在循环之前添加m = max(duration.values())
,并将循环中的if从if v == max(duration.values())
更改为if v == m
。它将每次都起作用。