In: Computer Science
In python, write a function, called ThreeSum, that accepts a list of non-negative numbers as input, and returns the highest sum of three neighboring elements in it. Write a main method that initializes the following five lists, gets the ThreeSum result for all of them using the above function, and prints the result to the screen. Example of the output: List 1: [4,5,4,5] , Three sum = 14 List 2: [7] , Three sum = 7 List 3: [ ] , Three sum = 0 List 4: [8,1] , Three sum = 9 List 5: [1,3,5,7,4,2,9] , Three sum = 16
(for any doubts pls menion in the comments section, if you are pleased with the answer , please do give a like:)
Steps:
Source Code(# comments are given)(screen shot of code is given after the code, refer it for indentation checking)
#function threesum with argument as list_1
def threeSum(list_1):
#max will store the threesums of all the list
#large will store the largest element in each list
max=[]
large=0
#n contains the length of list passed
n=len(list_1)
#checking conditions
if n<3:
sum=0
for i in list_1:
sum+=i
return sum
elif n<1:
sum=0
return sum
else:
for item in range(n-2):
pos=0
sum=0
if pos==0:
sum=list_1[item]
pos+=1
if pos==1:
sum+=list_1[item+1]
pos+=1
if pos==2:
sum+=list_1[item+2]
pos+=1
max.append(sum)
for l in max:
if l>large:
large=l
return large
#main function to call threeSum and print the sum
def main():
list1=[4,5,4,5]
list2=[7]
list3=[]
list4=[8,1]
list5=[1,3,5,7,4,2,9]
print(list1)
sum=threeSum(list1)
print("ThreeSum = "+str(sum))
print(list2)
sum=threeSum(list2)
print("ThreeSum = "+str(sum))
print(list3)
sum=threeSum(list3)
print("ThreeSum = "+str(sum))
print(list4)
sum=threeSum(list4)
print("ThreeSum = "+str(sum))
sum=threeSum(list5)
print(list5)
print("ThreeSum = "+str(sum))
main()
Screenshot of code
Screenshot of output