Python
 Computer >> コンピューター >  >> プログラミング >> Python

線形探索のためのPythonプログラム


この記事では、線形検索とPython3.xでの実装について学習します。またはそれ以前。

アルゴリズム

Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]
If x matches with any of the element, return the index value.
If x doesn’t match with any of elements in arr[] , return -1 or element not found.

次に、特定のアプローチの視覚的表現を見てみましょう-

線形探索のためのPythonプログラム

def linearsearch(arr, x):
   for i in range(len(arr)):
      if arr[i] == x:
         return i
      return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))

出力

element found at index 6

変数のスコープを図に示します-

線形探索のためのPythonプログラム

結論

この記事では、Python3.xでの線形検索のメカニズムについて学びました。またはそれ以前。


  1. バブルソート用のPythonプログラム

    この記事では、バブルソートの並べ替え手法の実装について学習します。 次の図は、このアルゴリズムの動作を示しています- アプローチ 最初の要素(インデックス=0)から始めて、現在の要素を配列の次の要素と比較します。 現在の要素が配列の次の要素よりも大きい場合は、それらを交換します。 現在の要素が次の要素よりも小さい場合は、次の要素に移動します。 手順1を繰り返します。 次に、以下の実装を見てみましょう- 例 def bubbleSort(ar):    n = len(arr)    # Traverse through

  2. 線形探索のためのPythonプログラム

    この記事では、線形検索とPython3.xでの実装について学習します。またはそれ以前。 アルゴリズム Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[] If x matches with any of the element, return the index value. If x doesn’t match with any of elements in arr[] , return -1 or element no