TAGS :Viewed: 19 - Published at: a few seconds ago

[ Maximum sum of sublist with a specific length ]

I'm supposed to write a function which takes two numbers, the first is a given number, and the second is the length for the maximum sublist that I'm supposed to find: for example input (1234,2) the output would be 7

this is my code so far, it just computes the sum of the entire digits:

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)

Answer 1


By what i get from question, this should do what you want:

def do(n, d):
    print sum(sorted([int(x) for x in str(n)])[-d:])

Answer 2


Let's clarify to make sure we're on the same page.

Inputs: 1) a list li of digits; 2) n

Output: the slice from li of length n that has maximal sum.

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

Answer 3


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

Answer 4


This should do the trick:

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

Answer 5


I think I understand what you're asking, and here is my solution. I've tested it on your input as well as other inputs with varying lengths of substring. This code finds the maximum sum of adjacent substrings in the input.

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)

So, for an input for the call sum_of_sublist(1234, 2), it will print the value 7 because the largest sum of 2 consecutive numbers is 3 + 4 = 7. Similarly, for the callsum_of_sublist(12531, 3), the program will print 10 because the largest sum of 3 consecutive numbers is 2 + 5 + 3 = 10.