【发布时间】:2020-02-16 06:16:32
【问题描述】:
我试图找出一个列表是否是一个严格递增的序列,如果 1 并且只有 1 个元素被删除。这适用于某些列表,但不适用于其他列表之间没有任何明显差异的列表。对于大型列表,它超过了执行时间限制。这是我的代码:
def almostIncreasingSequence(sequence):
for i in range(len(sequence)):
new_seq = sequence.copy()
del new_seq[i]
if all(i < j for i, j in zip(new_seq, new_seq[1:])):
output = True
else:
output = False
return output
我正在创建输入列表的副本。然后,我删除元素i,然后返回True 或False,具体取决于列表是否是严格递增的序列。我正在 for 循环中创建列表的副本,以确保我只删除一个元素。以下是代码未返回适当值的一些测试运行:
Input:
sequence: [10, 1, 2, 3, 4, 5]
Output: false
Expected Output: true
Input:
sequence: [1, 2, 5, 3, 5]
Output: false
Expected Output: true
并且在这个测试用例中,代码超过了执行时间限制:
Input:
sequence: [-9996, -9995, -9994, -9993, -9991, -9989, -9987, -9986, -9985, -9983, -9982, -9980, -9978, -9977, -9976, -9975, -9974, -9972, -9968, -9966, -9965, -9961, -9957, -9956, -9955, -9954, -9952, -9948, -9942, -9939, -9938, -9936, -9935, -9932, -9931, -9927, -9925, -9923, -9922, -9921, -9920, -9919, -9918, -9908, -9905, -9902, -9901, -9900, -9899, -9897, -9896, -9894, -9888, -9886, -9880, -9878, -9877, -9876, -9874, -9872, -9871, -9870, -9869, -9868, -9867, -9865, -9857, -9856, -9855, -9854, -9853, -9852, -9851, -9849, -9848, -9846, -9845, -9843, -9842, -9841, -9840, -9837, -9834, -9828, -9826, -9824, -9823, -9820, -9816, -9814, -9812, -9811, -9810, -9809, -9807, -9806, -9804, -9803, -9801, -9800]
Output: undefined
Expected Output: false
【问题讨论】:
-
性能问题很可能是算法的选择,而不是程序本身。
标签: python algorithm list for-loop