Respuesta :
Answer:
1. def SequenceSumClosestTo(vals,thisSum):
2. inf = float('-inf')
3. closestSum = [inf,inf,inf]
4. for i in range(len(vals)):
5. for j in range(len(vals)-i):
6. oneSum = sum(vals[i:j+i+1])
7. if oneSum == thisSum:
8. return([i,j+1,thisSum])
9. elif (thisSum > oneSum > closestSum[2]):
10. closestSum = [i,j+1,oneSum]
11. return(closestSum)
Explanation:
- On line 1 we define the functions
- On line 2 we define a minus infinity value to use as a reference
- On line 3 we define an array called closestSum to store the values of the closest sum at a given moment
- On line 4 we create a for loop to iterate over the the input vals
- On line 5 we create a for loop to check all the possible combinations for a given start value of vals
- On line 6 we define oneSum to store a partial sum at a given moment
- On line 7 we use an if statement to check if oneSum is the value we are expecting
- Line 8 will return the found value if the if statement in line 7 is True
- On line 9 we use an if statement to check if oneSum is better than closestSum and smaller than thisSum
- On line 10 If the else if statement is True, we have a better closestSum
- Finally on line 11 we return closestSum if no thisSum was found
