基本算法
找零钱: def doChange(lingqian,change,ret_num,ret_coin): for to_change in range(change+1): ret_num[to_change]=to_change for i in [j for j in lingqian if j<=to_change]: if ret_num[to_change]>ret_num[to_change-i]+1: ret_num[to_change]=ret_num[to_change-i]+1 ret_coin[to_change]=i def show_coin(ret_coin,change): while change>0: temp=ret_coin[change] print(temp) change=change-temp
快速排序: def mypart(lst,low,hight): flag=lst[low] while low<hight: while low<hight and flag<=lst[hight]: hight =hight- 1 lst[low]=lst[hight] while low<hight and flag>=lst[low]: low =low +1 lst[hight]=lst[low] lst[low]=flag return low def mysort(lst,low,hight): if low<hight: mid=mypart(lst,low,hight) mysort(lst,low,mid-1) mysort(lst,mid+1,hight) def quicksort(lst): mysort(lst,0,len(lst)-1) def quick_main(): lst=[11,2,34,52,26,66] quicksort(lst) print(lst)
词梯: from enum import Enum class COLORS(Enum): white=1 gray=2 black=3 class NODE(object): def __init__(self,value): self._value=value self.connections={} self._parent=None self._dis=None self._color=COLORS.white def addNeibor(self,item,weight=1): self.connections[item]=weight @property def value(self): return self._value @value.setter def value(self,value): self._value=value @property def parent(self): return self._parent @parent.setter def parent(self,item): self._parent=item @property def color(self): return self._color @color.setter def color(self,value): self._color=value def getNeibor(self): return self.connections.keys() def setParent(self,item): self.parent=item @property def dis(self): return self._dis @dis.setter def dis(self,value): self._dis=value class GRAPH(object): def __init__(self): self.sons={} self.size=0 def addSon(self,value): self.sons[value]=NODE(value) self.size +=1 def getSon(self,value): return self.sons.get(value,None) def addEdge(self,value1,value2,weight=1): if value1 not in self.sons: self.addSon(value1) if value2 not in self.sons: self.addSon(value2) self.sons[value1].addNeibor(self.sons[value2],weight) def genCiTi(datas): bkt={} g=GRAPH() for data in datas: for i in range(len(data)): flag=data[:i]+'_'+data[i+1:] bkt.setdefault(flag,[]).append(data) for _,data in bkt.items(): for word1 in data: for word2 in data: if word1 != word2: g.addEdge(word1,word2,1) return g def minPaht(g,start): path=[] first=g.getSon(start) first.dis=0 first.parent=None path.append(first) while len(path)>0: current=path.pop(0) for son in current.getNeibor(): if son.color == COLORS.white: newdis=current.dis+1 son.dis=newdis son.parent=current son.color=COLORS.gray path.append(son) current.color=COLORS.black def showPah(g,dest): item=g.getSon(dest) print(item.value) while item.parent: item=item.parent print(item.value) def mainCiTi(): datas=['fool', 'foul', 'foil', 'fail', 'poll', 'pall', 'pole', 'fall', 'page', 'sage', 'sale', 'pale', 'pope', 'cool', 'pool'] g=genCiTi(datas) minPaht(g,"fool") showPah(g,'sage') mainCiTi()