Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'Example binary chop search'
- def search(source, matching):
- 'search container <source> to find position of <matching>'
- 'return 0 for not found or position where found starting from 1'
- lower = 0
- upper = len(source) - 1
- while lower <= upper: # note the addition of the = sign
- middle = (lower + upper) // 2
- if source[middle] == matching:
- return middle + 1 # human's count from 1
- else:
- if source[middle] < matching:
- lower = middle + 1
- else:
- upper = middle - 1
- return 0
- original = [120,158,78,52,1859,2000,15,14,22,24,56]
- tests = original[:]
- tests.insert(3, 999) # number not in list, to check not found works
- original.sort()
- print('Sorted lists of numbers: ', end='')
- print(*original, sep=", ")
- print()
- for target in tests:
- pos = search(original, target)
- if pos: # 0 == False, not 0 == True
- print (f"{target:4} found at position {pos:3}")
- else:
- print(f"{target:4} not found")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement