如何在Python中附加重叠元组并按顺序列出它们?
我正在研究算法,其中一个问题是要我构建一个内部日历工具,它将数据存储为整数元组。我的目标是编写一个函数,它获取多个会议时间范围的列表并返回压缩范围的列表 到目前为止,我已经编写了伪代码和一些实际代码。然而,我试图附加重叠时间(用整数表示),我被卡住了。以下是我目前掌握的情况:如何在Python中附加重叠元组并按顺序列出它们?,python,algorithm,data-structures,Python,Algorithm,Data Structures,我正在研究算法,其中一个问题是要我构建一个内部日历工具,它将数据存储为整数元组。我的目标是编写一个函数,它获取多个会议时间范围的列表并返回压缩范围的列表 到目前为止,我已经编写了伪代码和一些实际代码。然而,我试图附加重叠时间(用整数表示),我被卡住了。以下是我目前掌握的情况: # Variable containing list of tuples meeting_times = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)] # Sort meetin
# Variable containing list of tuples
meeting_times = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
# Sort meetings by start time
ordered_list = sorted(meeting_times)
# For each number in the variable
for m in range(ordered_list):
# If number overlaps with another number in variable
if m[0:] >= m[:-1]:
# Append start time of first number to end time of last number
append_meeting_time =
else:
# Continue on and loop through variable.
虽然这还不完整,但我想知道我的道路是否正确。如果没有,我如何改进我的答案?假设您的会议时间不会重叠,因为您不能同时在两个地方。因此,(1,4)(3,5)不可能发生 一种方法是使用一个能记住上一个元组的变量进行迭代,在本例中,我将其命名为“previous”,我将保持变量“m”不变 每次在会议时间中进入下一个元组时,都会将上一个元组的结束会议时间与当前开始会议时间进行比较。然后删除上一个元组,因为它是重复的。如果没有压缩操作,那么您只需附加到列表,然后在下一次迭代中将“m”设置为“previous”
# Variable containing list of tuples
meeting_times = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
# Sort meetings by start time
ordered_list = sorted(meeting_times)
print('Given time tuple: ', ordered_list)
def condensed_meeting_time(append_meeting_time, previous):
# For each number in the variable
for m in ordered_list:
if previous: # This is to catch empty tuple that was initial
if m[0] == previous[1]: # If current starting meeting time is equal to previous ending meeting time ...
del append_meeting_time[-1] # Remove the previous element
append_meeting_time.append( (previous[0], m[1]) ) # Create new tuple to merge previous start time to current ending time
else: # If the time does not overlap, append normally and set current meeting time to 'previous' for next iteration
append_meeting_time.append(m)
previous = m
else: # Base case to append the first element.
append_meeting_time.append(m)
previous = m
return append_meeting_time
print('After condensed range: ',condensed_meeting_time([], ()))
这是我得到的输出:
Given time tuple: [(0, 1), (3, 5), (4, 8), (9, 10), (10, 12)]
After condensed range: [(0, 1), (3, 5), (4, 8), (9, 12)]
我希望这有帮助 你能使用库吗?或者这是一种受限的练习吗?我看不出在这么小的代码片段中编写伪代码和真实代码的好处。要么编写伪代码,要么编写真正的python。这段代码很容易测试!尝试一下,看看什么有效,什么无效。当你收到答案时,你可能已经通过尝试一些东西解决了这个问题。不,我不能使用图书馆。我做这些练习是为了准备不可避免的技术面试。它必须是普通的Python。不过,更多关于这个主题。你的if语句没有意义。您也不需要切片,因为您知道每个元组只有两个项。您可能需要这样的内容:
如果有序列表[m][1]>=有序列表[m+1][0]
。您仍然必须确保1这不会在最后一个索引上触发,2考虑两个以上的重叠元组,3要生成正确的输出。对于范围内的m(有序列表):
这是不起作用的,可能您的意思是对于范围内的m(len(有序列表)):
但是您必须调用有序列表[m][0:]
非常感谢,比萨饼!如果我在一次技术面试中被问到这个问题,我真的希望我能接近你的解决方案。