【问题标题】:A recursive function to check if element is in SORTED list检查元素是否在排序列表中的递归函数
【发布时间】:2021-03-10 08:04:36
【问题描述】:

我并不是很喜欢递归函数,我要求将我的函数更改为递归和更优化的函数。我知道在这个任务中我应该利用这个列表排序的事实,但我不知道如何,也许是一些冒泡排序?这是我的代码,非常简单但甚至不是递归的,它没有考虑列表是否排序。

list1 = [1, 2, 3, 4, 5, 6]


def is_in_List(x):
    if x in list1:
        return True
    else:
        return False


x = 3

if is_in_List(x):
    print(f"{x} is in list")
else:
    print(f"{x} is not in list")

【问题讨论】:

标签: python python-3.x list function recursion


【解决方案1】:

你能做的就是使用分而治之,这意味着:

算法是这样的:

您有一个包含 n 个元素的排序列表。如果 n/2 处的元素是您要查找的元素,则检查数组 如果不是,作为一个排序列表,你知道 n/2 -> n 的所有元素都更大,而 0 -> n/2 的所有元素都更小。检查 n/2 处的数字是否小于或大于您要搜索的数字。如果它更小,则再次运行相同的函数,但现在,你只给它列表的一个子集,这意味着,如果它更小,你给 0 -> n/2,如果它更大,你给 n/2 -> n .当然,您需要一些停止条件,但是,这就是算法。

这是理论,这是代码。

不是最好的实现,只是我的想法。

my_list = [1,2,3,4,5,6,7,8,9];


def binary_search(a_list, search_term):

    #get the middle position of the array and convert it to int    
    middle_pos = int((len(a_list)-1)/2)
    
    #check if the array has only one element, and if so it it is not equal to what we're searching for, than nothing is in the aray
    
    if len(a_list) == 1 and search_term != a_list[middle_pos] :
        #means there are no more elements to search through
        return False
    
    #get the middle term of the list
    middle_term = a_list[middle_pos]
    
    #check if they are equal, if so, the number is in the array
    if search_term == middle_term:
        return True
    
    #if the middle is less than search, it means we need to search in the list from middle to top
    if middle_term < search_term : 
        #run the same algo, but now on a subset of the given list
        return binary_search(a_list[middle_pos:len(a_list)], search_term)
        
    else : 
        #on else, it means its less, we need to search from 0 to middle
        #run the same algo, but now on a subset of the given list
        return binary_search(a_list[0:middle_pos], search_term)
        
print(binary_search(my_list, 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2018-08-19
    • 1970-01-01
    • 2016-05-07
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多