標籤:例子 pos 轉變 2.4 條件 亂序 else dss ppp
來源:https://legacy.gitbook.com/book/xidianwlc/python-data-structrue-and-algrothms/details
參考學習,代碼改進
2.4.一個亂序字串檢查的例子
#python#查詢s2中是否包含s1中的的字母是否相同def anagramSolution1(s1,s2): print(type(s1)) print(type(s2)) alist=list(s2) #將元組轉變為列表 pos1=0 stillOk=True while pos1<len(s1) and stillOk: pos2=0 found=False while pos2<len(alist) and not found: #當存在字母相同時,跳出迴圈 或不存在相同時跳出迴圈 if s1[pos1]==alist[pos2] and pos2==len(s1)-pos1-1: #加上pos2==len(s1)-pos1-1為迴文判斷 found=True #判定條件 else: pos2=pos2+1 if found: alist[pos2]=None else: stillOk=False pos1=pos1+1 return stillOkprint(anagramSolution1(‘abcd‘,‘abdc‘))print(anagramSolution1(‘abcd‘,‘d‘))#查詢s2中是否包含s1中的的字母是否相同,排序後篩選def anagramSolution2(s1,s2): alist1=list(set(s1)) #set()去重 alist2=list(set(s2)) alist1.sort() alist2.sort() print(alist1,alist2) pos=0 matches=True while pos<len(alist1) and matches: #len(alist1)計算alist1的長度,當s1=s2否者會報錯 if alist1[pos]==alist2[pos]: pos=pos+1 else: matches=False return matchesprint(anagramSolution2(‘abcdss‘,‘abcdddwdss‘))print(anagramSolution2(‘asbscde‘,‘asbscde‘))#計數和比較,s1 s2字母相同,且個數相同,排序不同c1=[0]*26 def anagramSolution4(s1,s2): c1=[0]*26 c2=[0]*26 for i in range(len(s1)): #計算每個字母出現的次數 pos=ord(s1[i])-ord(‘a‘) #ord()返回對應的 ASCII 數值,或者 Unicode 數值 計算與a數值大小 c1[pos]=c1[pos]+1 for i in range(len(s2)): pos=ord(s2[i])-ord(‘a‘) c2[pos]=c2[pos]+1 print(c1,c2) j=0 stillOK=True while j<26 and stillOK: #比較字母出現個數數量是夠相同 if c1[j]==c2[j]: j=j+1 else: stillOK=False return stillOKprint(anagramSolution4(‘appleppp‘,‘pleapppp‘))
演算法分析2.4-亂序字串檢查