|
| 1 | +def simpleTernarySearch(item_list): |
| 2 | + """ |
| 3 | + Find the maximum value in a strictly increasing and then strictly decreasing list |
| 4 | + N.B.- This method won't work if the list does not represent an unimodal function |
| 5 | + e.g. if the maximum value present in the first or last index of the list |
| 6 | + """ |
| 7 | + left, right = 0, len(item_list) - 1 |
| 8 | + |
| 9 | + found = False |
| 10 | + |
| 11 | + while left <= right: |
| 12 | + if (right - left) < 3: #Here 3 is the smallest range to divide the left and right value |
| 13 | + found = True |
| 14 | + break |
| 15 | + |
| 16 | + leftThird = left + (right - left) // 3 |
| 17 | + rightThird = right - (right - left) // 3 |
| 18 | + |
| 19 | + #To find the minimum in an unimodal function change the following comparison to > |
| 20 | + if item_list[leftThird] < item_list[rightThird]: |
| 21 | + left = leftThird |
| 22 | + else: |
| 23 | + right = rightThird |
| 24 | + |
| 25 | + return (left + right) // 2 |
| 26 | + |
| 27 | + |
| 28 | +def ternarySearch(func, left, right, absolutePrecision): |
| 29 | + """ |
| 30 | + Find maximum of unimodal function func() within [left, right] |
| 31 | + To find the minimum, reverse the if/else statement or reverse the comparison. |
| 32 | + """ |
| 33 | + while True: |
| 34 | + #left and right are the current bounds; the maximum is between them |
| 35 | + if abs(right - left) < absolutePrecision: |
| 36 | + return (left + right)/2 |
| 37 | + |
| 38 | + leftThird = left + (right - left)/3 |
| 39 | + rightThird = right - (right - left)/3 |
| 40 | + |
| 41 | + if func(leftThird) < func(rightThird): |
| 42 | + left = leftThird |
| 43 | + else: |
| 44 | + right = rightThird |
| 45 | + |
| 46 | + |
| 47 | +def ternarySearchRecursive(func, left, right, absolutePrecision): |
| 48 | + """ |
| 49 | + left and right are the current bounds. the maximum is between them |
| 50 | + """ |
| 51 | + if abs(right - left) < absolutePrecision: |
| 52 | + return (left + right)/2 |
| 53 | + |
| 54 | + leftThird = (2*left + right)/3 |
| 55 | + rightThird = (left + 2*right)/3 |
| 56 | + |
| 57 | + if func(leftThird) < func(rightThird): |
| 58 | + return ternarySearch(func, leftThird, right, absolutePrecision) |
| 59 | + else: |
| 60 | + return ternarySearch(func, left, rightThird, absolutePrecision) |
0 commit comments