import math array = [1, 2, 3, 4, 5, 6, 20, 21, 33, 37, 88, 89, 90, 121, 133, 137, 188, 189, 190, 220, 221, 233, 237, 288, 289, 290, 321, 333, 337, 388, 389, 390, 1121, 1133, 1137, 1188, 1189, 1190, 1220, 1221, 1233, 1237, 1288, 1289, 1290, 1321, 1333, 1337, 1388, 1389, 1390, 2121, 2133, 2137, 2188, 2189, 2190, 2220, 2221, 2233, 2237, 2288, 2289, 2290, 2321, 2333, 2337, 2388, 2389, 2390, 3121, 3133, 3137, 3188, 3189, 3190, 3220, 3221, 3233, 3237, 3288, 3289, 3290, 3321, 3333, 3337, 3388, 3389, 3390, 1] n = len(array) steps = 0; depth = 2 current = math.floor(n / depth) left = current - 1 right = current + 1 found = 0 # initialization, start in the middle of the list, not a bad guess. while (found == 0): steps += 1 found = 1 # if the left of the current index is larger, then the maximum must be that way. # go left (subtract) one half as far as we went last time. not max, so found is 0. if (array[int(left)] > array[int(current)]): if (n / depth > 1): depth *= 2 current -= math.floor(n / depth) else: current -= 1 left = current - 1 right = current + 1 found = 0 # if the right of the current index is larger, then the maximum must be that way. # go right (add) one half as far as we went last time. not max, so found is 0. if (array[int(right)] > array[int(current)]): if (n / depth > 1): depth *= 2 current += math.floor(n / depth) else: current += 1 left = current - 1 right = current + 1 found = 0 print "max: ", array[int(current)], " steps: ", steps, " entries: ", n # works only for truly unimodal lists, not lists with multiple terms of the same value adjacent each other.
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question