家庭作业:返回列表中k个连续元素的最大总和。我尝试了以下3个,它们用于验证解决方案的7个测试中的6个。第7次测试是一个非常长的输入,具有非常大的k值。我无法输入输入列表,因为显示的列表由于其长度而被截断。这是我尝试的3种方法。重复,每次都在,而最后一个也给了我SyntaxError
。
方法1:[详细]
def arrayMaxConsecutiveSum(inputArray, k):
sum_array = []
for i in range(len(inputArray)-(k+1)):
sum_array.append(sum(inputArray[i:i+k]))
return max(sum_array)
方法2:[一行=效率??]
def arrayMaxConsecutiveSum(inputArray, k):
return max([sum(inputArray[i:i+k]) for i in range(len(inputArray)-(k+1))])
方法3:Lambda调用
def arrayMaxConsecutiveSum(inputArray, k):
f = lambda data, n: [data[i:i+n] for i in range(len(data) - n + 1)]
sum_array = [sum(val) for val in f(inputArray,k)]
return max(sum_array)
输入和(正确)输出的一些示例:
同样,我想提一下,我通过了其他测试(6很长,k值也很大[k比一个小于7的数量级,但是])只需要确定一个方法或者一个更有效的修订/使这些更有效。最后,我想补充一点,我尝试在IDLE3上使用(截断的)输入6和7,每个输出都生成ValueError
:
Traceback (most recent call last):
File "/Users/ryanflynn/arrmaxconsecsum.py", line 15, in <module>
962, 244, 390, 854, 406, 457, 160, 612, 693, 896, 800, 670, 776, 65, 81, 336, 305, 262, 877, 217, 50, 835, 307, 865, 774, 163, 556, 186, 734, 404, 610, 621, 538, 370, 153, 105, 816, 172, 149, 404, 634, 105, 74, 303, 304, 145, 592, 472, 778, 301, 480, 693, 954, 628, 355, 400, 327, 916, 458, 599, 157, 424, 957, 340, 51, 60, 688, 325, 456, 148, 189, 365, 358, 618, 462, 125, 863, 530, 942, 978, 898, 858, 671, 527, 877, 614, 826, 163, 380, 442, 68, 825, 978, 965, 562, 724, 553, 18, 554, 516, 694, 802, 650, 434, 520, 685, 581, 445, 441, 711, 757, 167, 594, 686, 993, 543, 694, 950, 812, 765, 483, 474, 961, 566, 224, 879, 403, 649, 27, 205, 841, 35, 35, 816, 723, 276, 984, 869, 502, 248, 695, 273, 689, 885, 157, 246, 684, 642, 172, 313, 683, 968, 29, 52, 915, 800, 608, 974, 266, 5, 252, 6, 15, 725, 788, 137, 200, 107, 173, 245, 753, 594, 47, 795, 477, 37, 904, 4, 781, 804, 352, 460, 244, 119, 410, 333, 187, 231, 48, 560, 771, 921, 595, 794, 925, 35, 312, 561, 173, 233, 669, 300, 73, 977, 977, 591, 322, 187, 199, 817, 386, 806, 625, 500, 1, 294, 40, 271, 306, 724, 713, 600, 126, 263, 591, 855, 976, 515, 850, 219, 118, 921, 522, 587, 498, 420, 724, 716],6886)
File "/Users/ryanflynn/arrmaxconsecsum.py", line 6, in arrayMaxConsecutiveSum
return max(sum_array)
ValueError: max() arg is an empty sequence
(注意:这个用过的方法3)我用print语句检查f(inputArray,k)
和sum_array
的值:[]
任何帮助都将不胜感激:)
答案 0 :(得分:2)
尝试:
Function triangles_at_vertex(k):
Count = 0
kList = Adjacency_list(k)
For i in kList:
iList = Adjacency_list(i)
For j in iList:
If (j in kList):
Count = Count + 1
End If
End For
End For
Return Count / 2
End Function
S代表sum,M代表max。
当你的O(n * k)
时,这个解决方案的复杂度为O(n)当我将3个数字相加n次时,你正在将k个数相加n-k次。