Guest User

Untitled

a guest
Feb 19th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. """
  2. Given a list of float numbers, and four operators +, -, *, / with flat preference, find the maximum value by inserting operator between each consecutive pair of numbers.
  3.  
  4. For example, given the array [1, 12, -3], the maximum number 33 can be found using 1 - 12 * (-3), since all operators have flat preference, so 1 - 12 * (-3) will be handled from left to right, first operation is 1 - 12 with value -11, and then second operation is -11 * (-3) = 33.
  5.  
  6.  
  7. opt(i,j) = max value I can get from range i to j using all operators
  8.  
  9. opt(i, j) = max (operation <- +, -, *,/) {
  10. a[i] operation opt(i+1, j-1) operation a[j]
  11. }
  12.  
  13.  
  14. # 16 cases, +, +
  15. a[i] + opt(i+1, j-1) + a[j]
  16. a[i] + opt(i+1, j-1) - a[j]
  17. a[i] + opt(i+1, j-1) * a[j]
  18. a[i] + opt(i+1, j-1) / a[j]
  19.  
  20. opt(i) = max value I can get from range 0 to i
  21.  
  22. opt_min(i) = min value I can get from range 0 to i
  23.  
  24. .....i operator a[i]
  25.  
  26. opt(i) = max{
  27. opt(i-1) + a[i]
  28. opt(i-1) - a[i]
  29. opt(i-1) * a[i] # max
  30. opt(i-1) / a[i]
  31. opt_min(i-1) * a[i] # min
  32. opt_min(i-1) / a[i]
  33. }
  34.  
  35. opt_min(i) = min {}
  36. """
  37.  
  38. def max_value(array):
  39. l = len(array)
  40. opt = [0]*(l+1)
  41. opt_min = [0]*(l+1)
  42.  
  43. opt[1] = array[0]
  44. opt_min[1] = array[0]
  45.  
  46. for i in range(2, l+1):
  47. candidates = [opt[i-1]+a[i-1],
  48. opt[i-1]-a[i-1],
  49. opt[i-1]*a[i-1],
  50. opt[i-1]/a[i-1],
  51. opt_min[i-1]+a[i-1],
  52. opt_min[i-1]-a[i-1],
  53. opt_min[i-1]*a[i-1],
  54. opt_min[i-1]/a[i-1]]
  55.  
  56. opt[i] = max(candidates)
  57. opt_min[i] = min(candidates)
  58. print(opt)
  59. print(opt_min)
  60. return opt[l]
  61.  
  62. a=[1, 12, -3]
  63. print(max_value(a))
Add Comment
Please, Sign In to add comment