From eaede113f516a1045fdef080b7fce746601d2b32 Mon Sep 17 00:00:00 2001 From: Mantas Date: Thu, 6 Jun 2019 21:39:40 +0300 Subject: [PATCH 1/2] Add doctests for jump search algorithm You can run tests like this: python -m doctest searches/jump_search.py --- searches/jump_search.py | 45 +++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/searches/jump_search.py b/searches/jump_search.py index 10cb933f2f35..7ca689c2267d 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -1,12 +1,36 @@ -from __future__ import print_function -import math +""" +Jump search algorithm + + >>> arr = [ + ... 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, + ... ] + + >>> arr[jump_search(arr, 55)] + 55 + + >>> arr[jump_search(arr, 0)] + 0 + + >>> arr[jump_search(arr, 610)] + 610 + +Check if all arr at once: + + >>> all(arr[jump_search(arr, x)] == x for x in arr) + True + +""" + +from math import floor, sqrt + + def jump_search(arr, x): - n = len(arr) - step = int(math.floor(math.sqrt(n))) prev = 0 - while arr[min(step, n)-1] < x: + n = len(arr) + step = int(floor(sqrt(n))) + while arr[min(step, n) - 1] < x: prev = step - step += int(math.floor(math.sqrt(n))) + step += int(floor(sqrt(n))) if prev >= n: return -1 @@ -14,13 +38,8 @@ def jump_search(arr, x): prev = prev + 1 if prev == min(step, n): return -1 + if arr[prev] == x: return prev - return -1 - - -arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] -x = 55 -index = jump_search(arr, x) -print("\nNumber " + str(x) +" is at index " + str(index)); + return -1 From 4b2ad64f67fec1b54dd6f39d4192ec06c13a5603 Mon Sep 17 00:00:00 2001 From: cclauss Date: Fri, 19 Jul 2019 00:30:16 +0200 Subject: [PATCH 2/2] black jump_search.py --- searches/jump_search.py | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/searches/jump_search.py b/searches/jump_search.py index 7ca689c2267d..6613afa3a920 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -5,6 +5,14 @@ ... 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, ... ] + >>> arr[jump_search(arr, 55)] + 55""" +Jump search algorithm + + >>> arr = [ + ... 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, + ... ] + >>> arr[jump_search(arr, 55)] 55 @@ -24,6 +32,43 @@ from math import floor, sqrt +def jump_search(arr, x): + prev = 0 + n = len(arr) + step = int(floor(sqrt(n))) + while arr[min(step, n) - 1] < x: + prev = step + step += int(floor(sqrt(n))) + if prev >= n: + return -1 + + while arr[prev] < x: + prev = prev + 1 + if prev == min(step, n): + return -1 + + if arr[prev] == x: + return prev + + return -1 + + + >>> arr[jump_search(arr, 0)] + 0 + + >>> arr[jump_search(arr, 610)] + 610 + +Check if all arr at once: + + >>> all(arr[jump_search(arr, x)] == x for x in arr) + True + +""" + +from math import floor, sqrt + + def jump_search(arr, x): prev = 0 n = len(arr)