測試開發的技能之一就是需要掌握一些開發的語言,而針對于考察開發語言,業界內比較容易采用的方式就是考察各種算法。在此做一個簡單的總結(最近比較喜歡玩Python,所以都是以Python為例子,其它的語言類推。)
- 冒泡排序
- 遞歸
- 二叉樹遍歷算法
- 字符串的倒序輸出
冒泡排序
冒泡排序算法的運作如下:(從后往前)
比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。在這一點,最后的元素應該會是最大的數。
針對所有的元素重復以上的步驟,除了最后一個。
持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
實例:對列表 [2, 8, 4, 7, 5, 9, 0]進行冒泡排序
def bubble(bubbleList):
listLength = len(bubbleList)
while listLength > 0:
for i in range(listLength - 1):
if bubbleList[i] > bubbleList[i + 1]:
bubbleList[i] = bubbleList[i] + bubbleList[i + 1]
bubbleList[i + 1] = bubbleList[i] - bubbleList[i + 1]
bubbleList[i] = bubbleList[i] - bubbleList[i + 1]
listLength -= 1
print(bubbleList)
if __name__ == '__main__':
bubbleList = [2, 8, 4, 7, 5, 9, 0]
bubble(bubbleList)
遞歸
遞歸過程一般通過函數或子過程來實現。遞歸方法:在函數或子過程的內部,直接或者間接地調用自己的算法。
遞歸算法流程實例:要計算1-10的10位數字的乘積,直觀的算法是123456789,利用遞歸則思路是循環執行n*n-1,直到n=1時
def recursion(n):
if n == 1:
return 1
else:
return n * recursion(n-1)
print(recursion(10))
二叉樹遍歷算法
從二叉樹的遞歸定義可知,一棵非空的二叉樹由根結點及左、右子樹這三個基本部分組成。因此,在任一給定結點上,可以按某種次序執行三個操作:
⑴訪問結點本身(N),
⑵遍歷該結點的左子樹(L),
⑶遍歷該結點的右子樹(R)。
以上三種操作有六種執行次序:
NLR、LNR、LRN、NRL、RNL、RLN。
二叉樹.png
二叉樹的節點表示可以使用
class Node:
def __init__(self,value=None,left=None,right=None):
self.value=value
self.left=left
self.right=right
前序遍歷:根節點->左子樹->右子樹
中序遍歷:左子樹->根節點->右子樹
后序遍歷:左子樹->右子樹->根節點
def preTraverse(root):
if root==None:
return
print(root.value)
preTraverse(root.left)
preTraverse(root.right)
def midTraverse(root):
if root==None:
return
midTraverse(root.left)
print(root.value)
midTraverse(root.right)
def afterTraverse(root):
if root==None:
return
afterTraverse(root.left)
afterTraverse(root.right)
print(root.value)
實例:求二叉樹深度和寬度
求深度用遞歸;求寬度用隊列,然后把每層的寬度求出來,找出最大的就是二叉樹的寬度
import queue
class Node:
def __init__(self,value=None,left=None,right=None):
self.value=value
self.left=left
self.right=right
def treeDepth(tree):
if tree==None:
return 0
leftDepth=treeDepth(tree.left)
rightDepth=treeDepth(tree.right)
if leftDepth>rightDepth:
return leftDepth+1
if rightDepth>=leftDepth:
return rightDepth+1
def treeWidth(tree):
curwidth=1
maxwidth=0
q=queue.Queue()
q.put(tree)
while not q.empty():
n=curwidth
for i in range(n):
tmp=q.get()
curwidth-=1
if tmp.left:
q.put(tmp.left)
curwidth+=1
if tmp.right:
q.put(tmp.right)
curwidth+=1
if curwidth>maxwidth:
maxwidth=curwidth
return maxwidth
if __name__=='__main__':
root=Node('D',Node('B',Node('A'),Node('C')),Node('E',right=Node('G',Node('F'))))
depth=treeDepth(root)
width=treeWidth(root)
print('depth:',depth)
print('width:',width)
字符串倒序輸出
思路一:索引的方法
strA = input("請輸入需要翻轉的字符串:")
print (strA[::-1])
思路二:借組列表進行翻轉
strA = input("請輸入需要翻轉的字符串:")
order = []
for i in strA:
order.append(i)
order.reverse() #將列表反轉
print (''.join(order)) #將list轉換成字符串
后續還有的話會繼續添加的。