python基础算法

1.斐波那契数列 1 1 2 3 5 8 13
def get_fbnq(n):
    n1 = 1
    n2 = 1
    if n == 0 or n == 1:
        return 1
    for i in range(n - 1):
        n1, n2 = n2, n1 + n2
    return n2

print(get_fbnq(6))
2.二分法查找
list = [1, 5, 8, 9, 15, 60, 88, 99]


def my_get(list, n):
    first = 0
    last = len(list) - 1
    x = 0
    while first < last:
        mid = int((len(list) - 1) / 2)
        if n == list[mid]:
            return mid + x
        if n < list[mid]:
            list = list[:mid + 1]
        if n > list[mid]:
            x += mid + 1
            list = list[mid + 1:]


print(my_get(list, 99))


# 第二种方式

def get_my(list, n):
    first = 0
    last = len(list) - 1
    while first <= last:
        mid = (first + last) // 2
        if n == list[mid]:
            return mid
        elif n > list[mid]:
            first = mid + 1
        elif n < list[mid]:
            last = mid - 1


print(get_my(list, 99))
3.冒泡排序
import random

list = [random.randint(1, 100) for i in range(50)]


def maopao(list):
    for i in range(len(list)):
        for x in range(len(list)):
            if list[i] < list[x]:
                list[i], list[x] = list[x], list[i]
    return list


print(maopao(list))
4.快速排序
def kuap(list):
    if len(list) < 2:
        return list
    data = list[len(list) // 2]
    list.remove(data)
    left, right = [], []
    for i in list:
        if i < data:
            left.append(i)
        if i >= data:
            right.append(i)
    return kuap(right) + [data] + kuap(left)


print(kuap(list))
5.多线程
import threading
import random
result =[]
def thread_sum():
      result.append(sum(random.randint(1,10) for _ in range(1000000)))

threadings =[threading.Thread(target=threda_sum) for _ in range(8)]
for thread in threadings:
    thread.start()
for thread in threadings:
    thread.join()

print(result)

6.多进程

from multiprocessing import Pool
import random
def multi_sum(n):
    return sum(random.randint(1,10) for _ in range(1000000))

pool =Pool(process=8)
print(pool.map(multi_sum,range(8)))

你可能感兴趣的:(python基础算法)