Python程式遞歸線性搜尋數組中的元素

WBOY
發布: 2023-08-20 23:22:30
轉載
992 人瀏覽過

Python程式遞歸線性搜尋數組中的元素

線性搜尋是在陣列中搜尋元素最簡單的方法。它是一種順序搜尋演算法,從一端開始,並檢查陣列的每個元素,直到找到所需的元素。

遞歸是指一個函數呼叫自身,當使用遞歸函數時,我們需要使用任何循環來產生迭代。下面的語法示範了簡單遞歸函數的工作原理。

def rerecursiveFun():
   Statements
   ...   
   rerecursiveFun()
   ...
rerecursiveFun
登入後複製

遞歸地線性搜尋元素

從陣列中遞歸地線性搜尋一個元素,只能透過使用函數來實現。在Python中,要定義一個函數,我們需要使用def關鍵字。

在本文中,我們將學習如何在Python中遞歸線性搜尋數組中的元素。在這裡,我們將使用Python列表代替數組,因為Python沒有特定的資料類型來表示數組。

Example

我們將透過遞減數組的大小來遞歸呼叫函數 recLinearSearch()。如果數組的大小變成負數,表示該元素不在數組中,我們回傳 -1。如果找到匹配項,則傳回元素所在的索引位置。

# Recursively Linearly Search an Element in an Array  
def recLinearSearch( arr, l, r, x): 
   if r < l: 
      return -1
   if arr[l] == x: 
      return l 
   if arr[r] == x: 
      return r 
   return recLinearSearch(arr, l+1, r-1, x) 
     
lst = [1, 6, 4, 9, 2, 8]
element = 2
res = recLinearSearch(lst, 0, len(lst)-1, element) 
  
if res != -1:
   print('{} was found at index {}.'.format(element, res))
else:
   print('{} was not found.'.format(element))
登入後複製

輸出

2 was found at index 4.
登入後複製

Example

讓我們來看一個在陣列中搜尋元素的另一個例子。

# Recursively Linearly Search an Element in an Array  
def recLinearSearch(arr, curr_index, key):
   if curr_index == -1:
      return -1
   if arr[curr_index] == key:
      return curr_index
   return recLinearSearch(arr, curr_index-1, key)
arr = [1, 3, 6, 9, 12, 15]
element = 6
res = recLinearSearch(arr, len(arr)-1, element) 
  
if res != -1:
   print('{} was found at index {}.'.format(element, res))
else:
   print('{} was not found.'.format(element))
登入後複製

輸出

6 was found at index 2.
登入後複製

Example

以搜尋數組中的元素100為另一個例子。

# Recursively Linearly Search an Element in an Array  
def recLinearSearch(arr, curr_index, key):
   if curr_index == -1:
      return -1
   if arr[curr_index] == key:
      return curr_index
   return recLinearSearch(arr, curr_index-1, key)     
arr = [1, 3, 6, 9, 12, 15]
element = 100
res = recLinearSearch(arr, len(arr)-1, element) 
  
if res != -1:
   print('{} was found at index {}.'.format(element, res))
else:
   print('{} was not found.'.format(element))
登入後複製

輸出

100 was not found.
登入後複製

在上面的範例中,給定的陣列中找不到元素100。

這些是使用Python程式遞歸線性搜尋數組中元素的範例。

以上是Python程式遞歸線性搜尋數組中的元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!