i need to write a function that adds up consecutive digits in a number and returns the biggest sum of them. i wrote a function that receives to arguments, (m,t). m- stands for the number(int), and t (int also) stands for the numbers of consecutive digits to sum. now i want it to go through all the digits in the number and at the end to return me the max. i dont figure out why my code doesnt work:
def sum_digits(m, t):
str_m= str(m)
for i in range(len(str_m)):
if t+i<len(str_m):
num= str_n[i:t+i]
num1='+'.join(num)
num2= str(eval(num1))
lst= list(num2)
else:
break
return max (lst)
The reason yours doesn't work is that lst
is getting reset every iteration. I think you intended to set it at the beginning and add to it each iteration. Also:
Ahhhh!!!! You don't need eval
!
def max_sum(m, t):
digits = map(int, str(m))
max_sum = cur_sum = sum(digits[:t])
for i, x in enumerate(s[t:], t):
cur_sum += x - digits[i - t]
max_sum = max(max_sum, cur_sum)
return max_sum
Also, this has O(log m) running time (or O(n) if n is the number of digits in m), rather than the naive O(t * log m) (or O(t * n)).
>>> def maxSum(m, t):
... m = str(m)
... answer = 0
... for digits in (m[i:i+t] for i in range(len(m)-t+1)):
... answer = max(answer, sum(int(d) for d in digits))
... return answer
...
>>> maxSum(1234567, 3)
18
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.