以下內容學習自:
def
select_sort
(items, comp=
lambda x, y: x < y)
:"""簡單選擇排序"""
items = items[:]
for i in
range
(len
(items)-1
):min_index = i
for j in
range
(i +1,
len(items)):
if comp(items[j]
, items[min_index]):
min_index = j
items[i]
, items[min_index]
= items[min_index]
, items[i]
return items
def
bubble_sort
(items, comp=
lambda x, y: x > y)
:"""氣泡排序"""
items = items[:]
for i in
range
(len
(items)-1
):false
for j in
range
(i,len
(items)-1
- i)
:if comp(items[j]
, items[j +1]
):items[j]
, items[j +1]
= items[j +1]
, items[j]
true
ifbreak
return items
def
bubble_sort
(items, comp=
lambda x, y: x > y)
:"""攪拌排序(氣泡排序公升級版)"""
items = items[:]
for i in
range
(len
(items)-1
):false
for j in
range
(i,len
(items)-1
- i)
:if comp(items[j]
, items[j +1]
):items[j]
, items[j +1]
= items[j +1]
, items[j]
true
false
for j in
range
(len
(items)-2
- i, i,-1
):if comp(items[j -1]
, items[j]):
items[j]
, items[j -1]
= items[j -1]
, items[j]
true
ifbreak
return items
def
merge
(items1, items2, comp=
lambda x, y: x < y)
:"""合併(將兩個有序的列表合併成乙個有序的列表)"""
items =
index1, index2 =0,
0while index1 <
len(items1)
and index2 <
len(items2)
:if comp(items1[index1]
, items2[index2]):
) index1 +=
1else:)
index2 +=
1 items += items1[index1:
] items += items2[index2:
]return items
defmerge_sort
(items, comp=
lambda x, y: x < y)
:return _merge_sort(
list
(items)
, comp)
def_merge_sort
(items, comp)
:"""歸併排序"""
iflen
(items)
<2:
return items
mid =
len(items)//2
left = _merge_sort(items[
:mid]
, comp)
right = _merge_sort(items[mid:
], comp)
return merge(left, right, comp)
def
seq_search
(items, key)
:"""順序查詢"""
for index, item in
enumerate
(items)
:if item == key:
return index
return
-1
def
bin_search
(items, key)
:"""折半查詢"""
start, end =0,
len(items)-1
while start <= end:
mid =
(start + end)//2
if key > items[mid]
: start = mid +
1elif key < items[mid]
: end = mid -
1else
:return mid
return
-1
每天學點Python之tuple
元組就是乙個增加了限制的列表,主要的區別就是元組一旦確定就不能再修改。它們可以通過各自的建構函式相互轉化。元組與列表非常相似,但它有自己的優勢 元組比列表速度快,同樣遍歷一串數值,元組的速度比類表快 建立安全的變數,有些變數不想在建立後被修改 元組是可以當作字典的鍵和集合的值的,列表由於是變化的,雜...
每天學點Python之dict
字典用來儲存鍵值對,在python中同乙個字典中的鍵和值都可以有不同的型別。建立乙個空的字典有兩種方法 d d dict 而建立乙個包含元素的字典方法比較多,下面操作結果相同 a dict one 1,two 2,three 3 b c dict zip one two three 1,2,3 d ...
每天學點Python之Iterator
我們經常需要遍歷乙個物件中的元素,在python中這種功能是通過迭代器來實現的。每乙個迭代器可以通過反覆呼叫迭代器的 next 方法來返回建立該迭代器的物件中的後繼值。當沒有可用資料時,產生乙個stopinteration異常。此時,迭代器物件被耗盡,之後再呼叫 next 方法只會再次產生stopi...