输入一个以逗号分隔的整数的字符串,如:"-4,2,1,4,2,-1,2"
求连续数字的最大和,上面字符串最大连续整数和为:2+1+4+2=9
代码实现:
from functools import reduce import time
# 装饰器,检测运行时间 def time_check(func): def wapper(*args, **kwargs): start_time = time.time() result = func(*args,**kwargs) stop_time = time.time() print("消耗时间为:{}".format(round(stop_time-start_time,4))) return result return wapper @time_check def get_max_num(str_num):
"""
实现求取最大连续整数和
""" num_list = [int(x) for x in num_str.split(',')] lens = len(num_list) max_dict={} for i in range(lens): for j in range(i+1,lens+1): max_dict.update({ tuple(num_list[i:j]):reduce(lambda x,y:x+y,num_list[i:j]) }) new_num_dict = sorted(max_dict.items(),key=lambda x:x[1]) return new_num_dict[-1][1] if __name__ == "__main__": num_str = '4,-3,6,-3,8,3,-1,2,-1,5,9' max_num = get_max_num(num_str) print(max_num)