In this assignment, you must use variables, loops, if statements, your own function definitions and function calls to write the required functions. For now, you may not use any of the powerful functions available in python modules, with one exception: you may import functions from the math module. a) Write a function defined as: def SequenceSumClosestTo(vals,this Sum): vals: an array (list) containing numbers (integers and or floats) this Sum: a number (integer or float) return value: The starting location, length and sum of the first sequence of numbers in vals, whose sum is closest to this Sum. Example: if vals [1, 5, -2, 3, 5, 5, 3, 5, 2, -5, 3, 3, 1, 5] If this Sum = 11, this function would return 1,4,11 If thisSum = 12, this function would return 0,5,12 If this Sum = 31, this function would return 3,11,30

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    
Ver imagen mateolara11
ACCESS MORE