#找到最小的元素 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=[11,22,33,21,123] 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) testArr= [13,44,53,24,876,2] print(Quick_Sort(testArr))
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 return None test_list=[1,3,5,7,9,11,13,15,17,19,21] Item_Search(test_list,11)
#使用字典構建圖 graph={} graph["you"]=["Alice","Bob","Claire"] graph["Bob"]=["Anuj","Peggy"] graph["Alice"]=["Peggy"] graph["Claire"]=["Tom","Jonny"] graph["Anuj"]=[] graph["Peggy"]=[] graph["Tom"]=[] graph["Jonny"]=[] from collections import deque #簡單的判斷方法 def person_is_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_is_seller(person): print("the seller is {0}".format(person)) return True else: search_queue+=graph[person] searched.append(person) #將這我的標記爲檢查過 return False print(Search("you"))
fruits=set(["蘋果","香蕉","梨子","西瓜","草莓","橘子","荔枝","榴蓮"]) #箱子以及包含的水果 box={} box["b1"]=set(["蘋果","香蕉","西瓜"]) box["b2"]=set(["草莓","橘子","榴蓮"]) box["b3"]=set(["梨子","荔枝","草莓"]) box["b4"]=set(["香蕉","橘子"]) box["b5"]=set(["梨子","榴蓮"]) final_boxs=set() #最終選擇的箱子 #直到fruits爲空 while fruits: best_box=None #包含了最多的未包含水果的箱子 fruits_covered=set() #包含該箱子包含的全部未包含的水果 #循環迭代每一個箱子,並肯定它是否爲最佳箱子 for boxItem,fruitItem in box.items(): covered=fruits & fruitItem #計算交集 if len(covered)>len(fruits_covered): best_box=boxItem fruits_covered=covered fruits-=fruits_covered final_boxs.add(best_box) print(final_boxs)
原文出處:https://www.cnblogs.com/IAMTOM/p/10210497.htmlhtml