我收到错误
Traceback:
in <module>
in merge_ranges
TypeError: 'int' object is not iterable
有人可以建议问题是什么,也可以调试我使用代码
meets = [(1,3),(5,8),(8,14),(13,17)]
print '{} should be {}'.format(merge_ranges(meets))
def merge_ranges(meets):
#sort by start time
sorted_meetings = sorted(meets)
merged_meetings = sorted_meetings[0]
for current_meeting_start, current_meeting_end in sorted_meetings[1:]:
last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]
if (current_meeting_start <= last_merged_meeting_end):
merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end))
else:
merged_meetings.append((current_meeting_start, current_meeting_end))
# write the body of your function here
return merged_meetings
答案 0 :(得分:2)
您将变量merged_meetings
初始化为单个元组,但它应该是元组列表。
因此,您必须将merged_meetings
的初始化修改为
merged_meetings = [sorted_meetings[0]]
,测试用例的结果将是
[(1, 3), (5, 17)]
答案 1 :(得分:1)
您无法像以下两行一样更改元组:
merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_end)) # here
merged_meetings.append((current_meeting_start, current_meeting_end)) # and here
元组是不可改变的。你不仅使用元组,而且还要打开比你应该更多的值。
答案 2 :(得分:1)
问题出在这一行:
last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]
merged_meetings
是一个元组,比如说(1,3)
merged_meetings[-1]
是单个值,3。
您尝试解压缩3到2个变量,这是不可能的。