Python学习笔记(五)——递归与分治

一、递归

1.All recursive solutions must satisfy three rules or properties:

(1)A recursive solution must contain a base case

(2)A recursive solution must contain a recursive case

(3)A recursive solution must make progress toward the base case.

2.反向打印链表:

(1)brute force

# Print the contents of a singly linked list in reverse order. 
def printListBF(head):
    numNodes = 0
    curNode = head
    while curNode is not None:
        curNode = curNode.next
        numNodes += 1
    
    for i in range(numNodes):
        curNode = head
        for j in range(numNodes - 1):
            curNode = curNode.next
        print(curNode.data)

 

(2)基于栈

from lliststack import Stack
def printListStack():
    s = Stack()
    curNode = head
    while curNode is not None:
        s.push(curNode.data)
        curNode = curNode.next
    
    while not s.isEmpty():
        item = s.pop()
        print(item)

(3)使用递归

def printList(node):
    if node is not None:
        printList(node.next)
        print(node.data)


3.使用递归进行二分法搜索

# Performs a recursive binary search on a sorted sequence. 
def recBinarySearch(target, theSeq, first, last):
    # If the sequence cannot be subdivided further, we are done. 
    if first > last:
        return False    # base case 
    else:
        mid = (last + first) // 2
        if theSeq[mid] == target:
            return True
        elif target < theSeq[mid]:
            return recBinarySearch(target, theSeq, first, mid - 1)
        else:
            return recBinarySearch(target, theSeq, mid + 1, last)

 

4.使用递归进行幂运算

def exp(x, n):
    if n == 0:
        return 1
    result = exp(x*x, n//2)
    if n % 2 == 0:
        return result
    else:
        return x * result

5.The Eight-Queens Problem

未解决

 

你可能感兴趣的:(Python学习笔记)