[英]Maximum sum of sublist with a specific length
我應該編寫一個包含兩個數字的函數,第一個是給定的數字,第二個是我應該找到的最大子列表的長度:例如,輸入(1234,2)的輸出將是7
到目前為止,這是我的代碼,它只計算所有數字的總和:
def altsum_digits(n,d):
b=str(n)
c=[]
for digit in b:
c.append(int(digit))
maxthere=0
realmax=0
for a in str(d):
for i in c:
maxthere=max(0,(maxthere+int(i)))
realmax=max(maxthere,realmax)
maxthere==0
print(realmax)
根據我的疑問,這應該做您想要的:
def do(n, d):
print sum(sorted([int(x) for x in str(n)])[-d:])
讓我們澄清一下,以確保我們在同一頁面上。
輸入:1)數字列表li
; 2) n
輸出:長度為n
li
中具有最大和的切片。
li = [4,2,1,7,1,3,8,4,7,8,1]
n = 2
slices = (li[x:x+n] for x in range(len(li)-n+1))
max(map(sum,slices))
Out[113]: 15
def sublists(lst, n):
return (lst[i:i+n] for i in range(len(lst) - n + 1))
def max_sublist_sum(lst, n):
return max(sum(sub) for sub in sublists(lst, n))
max_sublist_sum([1,2,3,4], 2) # => 7
這應該可以解決問題:
def altsum_digits(n, d):
l = list(map(int, str(n)))
m = c = sum(l[:d])
for i in range(0, len(l)-d):
c = c - l[i] + l[i+d]
if c > m: m = c
print m
altsum_digits(1234,2)
>>> 7
我想我了解您的要求,這是我的解決方案。 我已經在您的輸入以及具有不同長度的子字符串的其他輸入上對其進行了測試。 此代碼查找輸入中相鄰子字符串的最大和 。
def sum_of_sublist(input, maxLength):
input_array = [int(l) for l in str(input)]
tempMax = 0
realMax = 0
for i in range(len(input_array) - (maxLength - 1)):
for inc in range(0, maxLength):
tempMax += input_array[i+inc]
if tempMax > realMax:
realMax = tempMax
tempMax = 0
print realMax
sum_of_sublist(1234, 2)
因此,對於調用sum_of_sublist(1234, 2)
,它將打印值7,因為2個連續數字的最大和為3 + 4 =7。類似地,對於調用sum_of_sublist(12531, 3)
,程序將打印10,因為3個連續數字的最大和為2 + 5 + 3 = 10。
假設您得到數字n和長度k。
您要做的是首先將n變成數字列表,然后使用大小為k的滑動窗口,在每一步中添加下一個數字,然后將第一個數字減去該滑動窗口,並跟蹤max_sum因此您可以在最后將其退回。
該函數看起來像這樣
def altsum_digits(n, k):
list_n = [int(x) for x in str(n)]
max_sum = sum(list_n[:k])
for i in range(k, len(list_n)):
current_sum = current_sum + list_n[i] - list_n[i - k]
max_sum = max(current_sum, max_sum)
return max_sum
這是一個O(n)解決方案,所以它比生成大小為k的所有子列表要好得多。 希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.