python中的一些算法

# 递归,尾递归
def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):

    if num == 1:
        return product
    return fact_iter(num - 1, num * product)

#菲波列切数列
def fibo(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fibo(n-1) + fibo(n-2)




#冒泡排序

tmp_list = [14,3,1,5,4,1.4,10]

for j in range(len(tmp_list)):
    for i in range(len(tmp_list)-j-1):
        if tmp_list[i]<tmp_list[i+1]:
            tmp = tmp_list[i]
            tmp_list[i] = tmp_list[i+1]
            tmp_list[i + 1] = tmp


print(tmp_list)

#二分排序
def bin_search(data_list, val):
    low = 0                         # 最小数下标
    high = len(data_list) - 1       # 最大数下标
    while low <= high:
        mid = (low + high) // 2     # 中间数下标

        if data_list[mid] == val:   # 如果中间数下标等于val, 返回
            return mid
        elif data_list[mid] > val:  # 如果val在中间数左边, 移动high下标
            high = mid - 1
        else:                       # 如果val在中间数右边, 移动low下标
            low = mid + 1
    return # val不存在, 返回None
ret = bin_search(list(range(1, 10)), 7)

#print(list(range(1, 10)))


# 选择排序
def selectsort(list, order=1):
    if not isinstance(order, int):
        raise TypeError('order类型错误')
    for i in range(len(list) - 1):
        # 记录最小位置
        min_index = i
        # 筛选出最小数据
        for j in range(i + 1, len(list)):
            if order == 1:
                if list[j] < list[min_index]:
                    min_index = j
            else:
                if list[j] > list[min_index]:
                    min_index = j
            # 交换位置
            if min_index != i:
                list[i], list[min_index] = list[min_index], list[i]
    print(list)

selectsort([1, 4, 9, 6, 3, 100], 1)

转载自:https://blog.csdn.net/weixin_34292959/article/details/87545963

You may also like...

退出移动版