Add Python doctest to linear search (#195)

* Add Python doctest to linear search

* Fix conflict

* Rename linear-search.py to linear_search.py
pull/214/head
Christian Clauss 2021-04-16 14:31:38 +02:00 committed by GitHub
parent eb037403b8
commit 261739f943
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 9 deletions

View File

@ -1,12 +1,17 @@
def linear_search(a, x): arr = [1, 4, 7, 9, 14, 17, 39, 56]
for i in range(len(a)): targets = (8, 39)
if a[i] == x:
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 i
return -1 return -1
a = [1,4,7,9,14,17,39,56]
x = 8
y = 39
print(linear_search(a,x)) for target in targets:
print(linear_search(a,y)) print(f"linear_search({arr}, {target}) = {linear_search(arr, target)}")