zoukankan      html  css  js  c++  java
  • 算法基础与排序

    算法(Algorithm):一个计算过程,解决问题的方法

    程序等于数据结构加算法

    数据结构表现在python中,就是列表,元组,字典和集合等,就是变量和对象等

    程序的运行过程就是靠算法,一个函数就是一个算法

    参数就是输入经过算法,

    算法基础之递归

    递归有两个特点:
        调用自身
        必须要有结束条件
    

    例子一

        def func1(x):
            if x>0:
                print("func1:",x)
                func1(x-1)
        
        def func2(x):
            if x>0:
                func2(x-1)
                print("func2:",x)
    

    输入结果:

    func1: 5
    func1: 4
    func1: 3
    func1: 2
    func1: 1
    
    func2: 1
    func2: 2
    func2: 3
    func2: 4
    func2: 5
    

    递归之斐波那契数列

        def fibo_func(x):
        
            if x==1 or x==2:
                print(1)
            else:
                return fibo_func(x-1) + fibo_func(x-2)
        
        res=fibo_func(10)
    

    算法基础之列表查找

    列表查找:从列表中查找指定的元素
    输入:列表,待查找元素
    输出:元素下标或未查找到元素
    

    顺序查找:从列表的第一个元素开始,顺序进行搜索,直到找到为止

        l1=[5,7,4,6,3,1,2,9,8]
        
        def liner_search(data_set,val):
            for i in range(len(data_set)):
                if data_set[i]==val:
                    return i
            return
        
        print(liner_search(l1,6))
    

    二分查找

    从有序列表的候选区data[0:n]开始,通过对待查找的值与候选区中间值的比较,可以使候选区减少一半

        l1=[5,7,4,6,3,1,2,9,8]
        
        def bin_search(data_set,val):
            low=0
            high=len(data_set)-1
        
            while low <= high:
                mid=(low+high)//2
        
                if data_set[mid]==val:
                    return mid
                elif data_set[mid] > val:
                    high=mid-1
        
                else:
                    low=mid +1
        
                return
        
        print(bin_search(l1,3))
    

    二分查找的递归版本

        def bin_search_rec(data_set,val,low,high):
            if low <= high:
                mid=(low+high)//2
        
                if data_set[mid] ==val:
                    return mid
                elif data_set[mid] >val:
                    return bin_search_rec(data_set,val,low,mid-1)
                else:
                    return bin_search_rec(data_set,val,mid+1,high)
        
            else:
                return
  • 相关阅读:
    MAC配置DNS服务器
    真机IOS8.3以上的文件夹共享
    appium + python的环境配置_windows
    python 的时间与日期
    sublimetext 2 编译文件带input时 提示 EOFError: EOF when reading a line
    cmd无法输入中文解决方案
    配置python学习环境遇到的问题:[Decode error
    monkey初接触
    Android logcat输出中文乱码
    运行 命令框不记录打过的命令,重启后CMD里面是空的.上次打过的命令消失了.
  • 原文地址:https://www.cnblogs.com/renpingsheng/p/7795876.html
Copyright © 2011-2022 走看看