Python编程题总结

1 数学篇

1.1 斐波那契数列

def fib(n):
    if n in (0, 1):
        return n
    fib_n1, fib_n2 = 0, 1
    for i in range(2, n + 1):
        fib_n2, fib_n1 = fib_n2 + fib_n1, fib_n2
    return fib_n2

1.2 杨辉三角

def triangles():
    l = [1]
    while 1:
        yield l
        l = [1] + [l[n] + l[n + 1] for n in range(len(l) - 1)] + [1]

1.3 最大公约数

def gcd(x, y):
    return x  if (y == 0) else gcd(y, x % y)

1.4 最小公倍数

def gmd(x, y):
    return x * y // gcd(x, y)

1.5 求幂运算

def my_power(x, n):
    if n == 0:
        return 1
    if n < 0:
        return 1.0 / my_power(x, -n)
    tmp = my_power(x, n >> 1)
    if n & 1:
        return x * tmp * tmp
    else:
        return tmp * tmp

1.6 平方根

def binary_sqrt(x):
    start, end = 0, x
    while start <= end:
        middle = (start + end) // 2
        if x // middle == middle:
            return middle
        if x // middle > middle:
            start = middle + 1
        else:
            end = middle - 1
            
def newton_sqrt(x):
    result = x
    while x // result < result:
        result = (result + x // result) >> 1
    return result

2 数组篇

2.1 数组中重复的数字

def duplicate(arr):
    for i in range(0, len(arr)):
        while arr[i] != i:
            if arr[i] == arr[arr[i]]:
                return arr[i]
            else:
                arr[i], arr[arr[i]] = arr[arr[i]], arr[i]

2.2 二维数组的查找

def find(matrix, target):
    rows, cols = len(matrix), len(matrix[0])
    row, col = 0, cols - 1
    while row <= rows - 1 and col >= 0:
        diff = matrix[row][col] - target
        if diff == 0:
            return True
        elif diff > 0:
            col -= 1
        else:
            row += 1
    return False

2.3 旋转数组的最小数字

def find_min(arr):
    left = 0
    right = len(arr) - 1
    if arr[left] < arr[right]:
        return arr[left]
    while left <= right:
        middle = (left + right) >> 1
        if arr[middle] == arr[left] and \
            arr[middle] == arr[right]:
            return arr_min(arr, left, right)
        if arr[middle] > arr[left]:
            left = middle
        else:
            right = middle
        if left == right - 1:
            break
    return arr[right]

def arr_min(arr, left, right):
    result = arr[left]
    for x in range(left, right + 1):
        if arr[x] < result:
            result = arr[x]
    return result

2.4 数组中倒数第k大的数

def partion(arr, left, right):
    # 快排获取索引
        value = arr[right]
        start = left
        for i in range(left, right + 1):
            if arr[i] < value:
                if i != start:
                    arr[i], arr[start] = arr[start], arr[i]
                start += 1
        arr[right] = arr[start]
        arr[start] = value
        return start

def krth_num(arr, k):
    #倒数第k大的数
    assert 1 <= k <= len(arr), 'Out of boundary.'
    start = 0
    end = len(arr) - 1
    index = partion(arr, start, end)
    while index != len(arr) - k:
        if index > len(arr) - k:
            end = index - 1
            index = partion(arr, start, end)
        else:
            start = index + 1
            index = partion(arr, start, end)
    return arr[index]

2.5 连续子数组的最大和

 

3 链表篇

class ListNode:
    def __init__(self):
        self.value = 0
        self.next = None
    def print_list(self):
        tmp = self
        while tmp:
            print(tmp.value)
            tmp = tmp.next

3.1 从尾到头打印链表

def print_list_reverse(list_node):
    arr = []
    while list_node:
        arr.append(list_node.value)
        list_node = list_node.next
    while arr:
        print(arr.pop())

3.2 链表的反转

def reverse_list(root):
    pre = None
    while root:
        next = root.next
        root.next = pre
        pre = root
        root = next
    return pre

 

3.3 合并两个排序的链表

def merge_list(root_a, root_b):
    if not root_a:
        return root_b
    if not root_b:
        return root_a
    if root_a.value < root_b.value:
        root = root_a
        root.next = merge_list(root_a.next, root_b)
    else:
        root = root_b
        root.next = merge_list(root_a, root_b.next)
    return root

3.4 删除链表的节点

def delete_node(root, target):
    if root is target:
        root.next = None
        return

    if target.next:
        target.value = target.next.value
        target.next = None
    else:
        while root.next is not target:
            root = root.next
        root.next = None

4 二叉树篇

class BinaryTreeNode:
    def __init__(self, value = 0, left = None, right = None):
        self.value = value
        self.left, self.right = left, right

    def print_tree(self):
        if self.left:
            self.left.print_tree()
        print(self.value)
        if self.right:
            self.right.print_tree()

4.1 重建二叉树

def rebult_tree(arr1, arr2):
    return rebult_tree_rec(arr1, 0, len(arr1) - 1, arr2, 0, len(arr2) - 1)

def rebult_tree_rec(arr1, left1, right1, arr2, left2, right2):
    if left1 > right1 or left2 > right2:
        return None
    root = BinaryTreeNode()
    root.value = arr1[left1]
    index = arr2.index(arr1[left1])
    root.left = rebult_tree_rec(arr1, left1 + 1, left1 + index - left2, arr2, left2, index - 1)
    root.right = rebult_tree_rec(arr1, left1 + index - left2 + 1, right1, arr2, index + 1, right2)
    return root

4.2 二叉树的下一个节点

class BinaryTreeNode:
    def __init__(self):
        self.value = 0
        self.left, self.right = None, None
        self.father = None

def next_node(node):
    if node.right:
        node = node.right
        while node.left:
            node = node.left
        return node
    else:
        while node.father:
            if node.father.left is node:
                return node.father
            node = node.father
    return None

4.3 二叉树的镜像

def mirror_tree(root):
    if not root:
        return
    if not root.left and not root.right:
        return
    root.left, root.right = root.right, root.left
    if root.left:
        mirror_tree(root.left)
    if root.right:
        mirror_tree(root.right)

 

def is_sym_tree(root):
    return is_sym(root, root)
def is_sym(root1, root2):
    if not root1 and not root2:
        return True
    if not root1 or not root2:
        return False
    if root1.value != root2.value:
        return False
    return is_sym(root1.right, root2.left) and \
           is_sym(root2.left, root1.right)

4.4 二叉树的深度

4.5 从上到下打印二叉树

def print_tree_up_down(root):
    if not root:
        return
    queue_data = Queue()
    queue_data.put(root)
    while queue_data:
        node = queue_data.get()
        print(node.value)
        if node.left:
            queue_data.put(node.left)
        if node.right:
            queue_data.put(node.right)

4.6 二叉数的第k大节点

 

4.7 二叉搜索树与双向链表

class Solution:
    @classmethod
    def Convert(cls, pRootOfTree):
        cls.linkedlistLast = None
        cls.convertNode(pRootOfTree)
        pHead = cls.linkedlistLast
        while pHead.left:
            pHead = pHead.left
        return pHead

    @classmethod
    def convertNode(cls, root):
        if not root:
            return
        if root.left:
            cls.convertNode(root.left)
        root.left = cls.linkedlistLast
        if cls.linkedlistLast:
            cls.linkedlistLast.right = root
        cls.linkedlistLast = root
        if root.right:
            cls.convertNode(root.right)

5 栈与队列

5.1 两个栈实现队列

class MyQueue:
    stack1 = []
    stack2 = []

    def append_tail(self, item):
        self.stack1.append(item)

    def delete_head(self):
        while self.stack1:
            self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

5.2 两个队列实现栈

class MyStack:
    def __init__(self):
        self.q1 = Queue()
        self.q2 = Queue()
        
    def pop(self):
        '''
        弹出元素
        '''
        if self.q1.empty() and self.q2.empty():
            raise BaseException('Empty queue.')
        if self.q2.empty():
            while self.q1.qsize() > 1:
                self.q2.put(self.q1.get())
            return self.q1.get()
        if self.q1.empty():
            while self.q2.qsize() > 1:
                self.q1.put(self.q2.get())
            return self.q2.get()
        
    def push(self, item):
        '''
        插入元素
        '''
        if self.q1.empty():
            self.q2.put(item)
        if self.q2.empty():
            self.q1.put(item)

 

5.3 包含min/max函数的栈

class MyStack:
    def __init__(self):
        self.stack_data = []
        self.stack_min = []
        self.stack_max = []

    def push(self, value):
        self.stack_data.append(value)
        if not self.stack_min or value < self.stack_min[-1]:
            self.stack_min.append(value)
        else:
            self.stack_min.append(self.stack_min[-1])

        if not self.stack_max or value > self.stack_max[-1]:
            self.stack_max.append(value)
        else:
            self.stack_max.append(self.stack_max[-1])

    def pop(self):
        assert self.stack_min and self.stack_data
        self.stack_data.pop()
        self.stack_min.pop()
        self.stack_max.pop()

    def min(self):
        assert self.stack_min and self.stack_data
        return self.stack_min[-1]

    def max(self):
        assert self.stack_min and self.stack_data
        return self.stack_max[-1]

 

转载于:https://www.cnblogs.com/ik-heu/p/8922789.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值