2、排序比較法
計數比較法
def
bian_wei_ci
(ls1,ls2)
: alist=
list
(ls2)
pos1=
0 result=
true
#print(len(ls1))
iflen
(ls1)
==len
(ls2)
:while pos1<
len(ls1)
and result:
pos2=
0 found=
false
while pos2<
len(alist)
andnot found:
if ls1[pos1]
== alist[pos2]
: found=
true
else
: pos2=pos2+
1if found:
alist[pos2]
=none
else
: result=
false
break
pos1=pos1+
1return result
else
: result=
false
return result
問題規模:詞中包含的字元個數n
主要部分在兩重迴圈:外層迴圈遍歷s1每個字元,將內層迴圈執行n次,而內層迴圈在s2中查詢字元,每個字元的對比次數是1、2……n中的乙個,各不相同,取平均為(n+1)/2
所以執行次數是n*(n+1)/2
所以數量級o(n的平方)
def
bian_wei_ci2
(ls1,ls2)
: list1=
list
(ls1)
list2=
list
(ls2)
list1.sort(
) list2.sort(
) result=
true
pos=0if
len(list1)
==len
(list2)
:while pos<
len(list1)
and result:
if list1[pos]
==list2[pos]
: pos +=
1else
: result=
false
return result
else
: result=
false
return result
乍一看這個方法只有乙個迴圈,最多執行n次,數量級是o(n),但是迴圈前面的兩次sort()並不是沒有代價的,排序演算法採用不同的解決方案其執行時間差不多是o(n的平方)或者o(nlogn),大過迴圈o(n)
所以本演算法時間主導的步驟是排序步驟,本演算法執行時間數量級等於排序過程的數量級o(nlogn)
def
bian_wei_ci3
(ls1,ls2)
: c1=[0
]*26 c2=[0
]*26for i in
range
(len
(ls1)):
pos=
ord(ls1[i])-
ord(
'a')
c1[pos]
=c1[pos]+1
for i in
range
(len
(ls2)):
pos=
ord(ls2[i])-
ord(
'a')
c2[pos]
=c2[pos]+1
j=0 result=
true
while j<
26and result:
if c1[j]
==c2[j]
: j+=
1else
: result=
false
return result
計數比較演算法中有3個迴圈迭代,但不像解法一那樣存在巢狀迴圈
其總操作次數為2n+26,其數量級為o(n)
值得注意的是,本演算法依賴於兩個長度為26的計數器列表,來儲存字元計數,這相比於前兩個演算法需要更多的儲存空間。這種犧牲儲存空間來換取執行時間,或者相反,這種在時間空間之間的取捨和權衡,在選擇問題的解決過程中經常會出現。
python類的三種方法
python類有三種方法。1.一般方法,即不加任何修飾的,直接用def定義的方法。如 in 14 class a def a self print 一般方法 in 15 class a a in 16 class a.a 一般方法2.staticmethod方法 經過staticmethod修飾過的...
python列表逆序三種方法
栗子 題目 將乙個陣列逆序輸出。程式分析 用第乙個與最後乙個交換。import random list random.randint 0,100 for in range 21 print list 數應該先排序 defbubblesort arr for i in range 1,len arr ...
python 字典訪問的三種方法
定義字典 dic for key in dic print key,dic key print key str dic key 結果 a hello ahello c you cyou b how bhow 細節 print key,dic key 後面有個逗號,自動生成乙個空格 print key...