python 算法来了

本贴最后更新于 1575 天前,其中的信息可能已经时异事殊

# 找到最小的元素
def FindSmall(list):
    min=list[0]
    for i in range(len(list)):
        if list[i]<min:
            min=list[i]
    return min
# 选择排序
def Select_Sort(list):
    newArr=[]
    for i in range(len(list)):
        minValue=FindSmall(list)
        newArr.append(minValue)
        list.remove(minValue)
    return newArr
testArr=[10,32,37,21,223]
print(Select_Sort(testArr))

# 快速排序
def Quick_Sort(list):
    if len(list)<2:
        return list
    else:
        temp=list[0]
        less=[i for i in list[1:]if i<temp]
        more=[i for i in list[1:]if i>temp]
        return Quick_Sort(less)+[temp]+Quick_Sort(more)
testAry=[13,34,63,24,576,2]
print(Quick_Sort(testAry))

# 二分查找
def Item_Search(list,item):
    low=0
    high=len(list)-1
    while low<=high:
        middle=(low+high)//2
        print(list[middle])
        if list[middle]>item:
            high=middle-1
        elif list[middle]<item:
            low=middle+1
        else:
            return middle
test_list=[1,3,5,7,9,11,13,15,17,19,21]
Item_Search(test_list,11)
# print(Item_Search(test_list,11))

#  广度优先搜索
graph={}
graph["coco"]=["william","jack","joy"]
graph["jack"]=["any","boy"]
graph["william"]=["tom"]
graph["joy"]=["ku","jom"]
graph["any"]=[]
graph["boy"]=[]
graph["ku"]=[]
graph["jom"]=[]
from collections import deque
def person_seller(name):
    return name=='tom'
def Search(name):
    searched=[]   # 用于记录检查过的人,防止进入死循环
    search_queue=deque()  # 创建队列
    search_queue+=graph[name]
    while search_queue:
        person=search_queue.popleft()
        if not person in searched:    # 仅当这个人没检查过时才检查
            if person_seller(person):
                print("the seller is {0}".format(person))
                return True
            else:
                search_queue+=graph[person]
                searched.append(person)  # 将这个人标记为检查过
    return False
print(Search("coco"))

# 贪婪算法
fruits=set(["苹果","猕猴桃","沙棘果","西瓜","樱桃","空心李","橙子","地瓜"])
box={}
box["b1"]=set(["苹果","西瓜","橙子"])
box["b2"]=set(["猕猴桃","地瓜","沙棘果"])
box["b3"]=set(["空心李","樱桃","苹果"])
box["b4"]=set(["猕猴桃","橙子"])
box["b5"]=set(["沙棘果","地瓜"])
final_boxs=set()
while fruits:
    best_box=None
    fruits_covered=set()
    for boxItem,fruitsItem in box.items():
        covered=fruits & fruitsItem
        if len(covered)>len(fruits_covered):
            best_box=boxItem
            fruits_covered=covered
    fruits-=fruits_covered
    final_boxs.add(best_box)
print(final_boxs)
回帖
请输入回帖内容 ...