作業:返回列表中k個連續元素的最大總和。我已經嘗試了以下3種方法,這些方法在驗證解決方案的7個測試中有6個適用。第七個測試是一個非常長的輸入,具有非常大的k值。我不能放入輸入列表,因爲顯示的列表由於其長度而被截斷。這是我嘗試的3種方法。重申,每次超時,而最後一個也給了我一個SyntaxError
。 方法1:[詳細]Python。作業:由於輸入效率較高而不工作
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)
一些輸入和實例(正確)輸出:
- IN:[2,3,5, 1,6] K:2 OUT:8
- IN:[2,4,10,1] K:2 OUT:14
- IN:[1,3,4,2,4,2, 4] K:4 OUT:13
同樣,我想提一下,我通過其他試驗(6很長的大的k值以及[K值是幅度小於一個數量級7的,然而]),只需要確定一種更有效的方法或修訂版本,以提高效率。最後,我想補充一點,我試圖既6和7與IDLE3的(截短的)輸入和每個生成的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)I與打印語句檢查兩個值f(inputArray,k)
和sum_array
:[]
任何幫助,將不勝感激:)
這個列表到底有多長?第6次測試中'k'的值是多少? – Will
@wilusdaman k:6886測試6 –