python Python中的数据结构和算法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python中的数据结构和算法相关的知识,希望对你有一定的参考价值。

def factorial(n):
    """
    Calculate n!.
    Run in O(n) time, as there are n + 1 activations, each of which accounts for O(1) operations.
    """
    if n==0:
        return 1
    else:
        return n*factorial(n-1)
    

def binary_search(data, target, low, high):
    """
    Return True if target is found in indicated portion of a Python list.
    Run in O(log n) time.
    """
    if low > high:
        return False
    else:
        mid = (low + high) // 2
        if target == data[mid]:
            return True
        elif target < data[mid]:
            binary_search(data, target, low, mid - 1)
        else:
            binary_search(data, target, mid + 1, high)    
            
            
def disk_usage(path):
    """
    Return the number of bytes used by a file/folder and any descendents.
    """
    import os
    total = os.path.getsize(path)
    if os.path.isdir(path):
        for filename in os.listdir(path):
            child_path = os.path.join(path, filename)
            total += disk_usage(child_path)
    return total
    
    
def fibonacci(n):
    """
    Return pair of Fibonacci numbers, F(n) and F(n - 1).
    """
    if n <= 1:
        return (n, 0)
    else:
        a, b = fibonacci(n - 1)
        print("a, b: ", a, b)
        return (a + b, a)
    
    
def linear_sum(S, n):
    """
    Return the sum of the first n numbers of sequence S.
    """
    if n==0:
        return 0
    else:
        return S[n - 1] + linear_sum(S, n - 1)

以上是关于python Python中的数据结构和算法的主要内容,如果未能解决你的问题,请参考以下文章

python数据结构与算法

Python中的Apriori关联算法-市场购物篮分析

钉钉扫码登录中的签名算法在python中的实现

python 使用Python中的t-SNE算法可视化数据

Python中的拓扑排序算法(DFS)实现

数据结构-排序算法原理和Python实现