Add Python doctest to linear search (#195)
* Add Python doctest to linear search * Fix conflict * Rename linear-search.py to linear_search.pypull/214/head
parent
eb037403b8
commit
261739f943
|
@ -1,12 +1,17 @@
|
|||
def linear_search(a, x):
|
||||
for i in range(len(a)):
|
||||
if a[i] == x:
|
||||
arr = [1, 4, 7, 9, 14, 17, 39, 56]
|
||||
targets = (8, 39)
|
||||
|
||||
|
||||
def linear_search(arr, target):
|
||||
"""
|
||||
>>> all(linear_search(arr, x) == arr.index(x) if x in arr else -1 for x in targets)
|
||||
True
|
||||
"""
|
||||
for i, item in enumerate(arr):
|
||||
if item == target:
|
||||
return i
|
||||
return -1
|
||||
|
||||
a = [1,4,7,9,14,17,39,56]
|
||||
x = 8
|
||||
y = 39
|
||||
|
||||
print(linear_search(a,x))
|
||||
print(linear_search(a,y))
|
||||
|
||||
for target in targets:
|
||||
print(f"linear_search({arr}, {target}) = {linear_search(arr, target)}")
|
||||
|
|
Loading…
Reference in New Issue