python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

Posted cui_yonghua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)相关的知识,希望对你有一定的参考价值。

一. python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)

二. python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

三. python3的各种经典案例,总共299个案例,直接可以运行(后:99个案例))

【例101】插入区间 难度等级★★
3.代码实现

class Interval(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end
    def get(self):
        str1 = "(" + str(self.start) + "," + str(self.end) + ")"
        return str1
    def equals(self, Intervalx):
        if self.start == Intervalx.start and self.end == Intervalx.end:
            return 1
        else:
            return 0
class Solution:
    #参数intevals: 已排序的非重叠区间列表
    #参数newInterval: 新的区间
    #返回值: 一个新的排序非重叠区间列表与新的区间
    def insert(self, intervals, newInterval):
        results = []
        insertPos = 0
        for interval in intervals:
            if interval.end < newInterval.start:
                results.append(interval)
                insertPos += 1
            elif interval.start > newInterval.end:
                results.append(interval)
            else:
                newInterval.start = min(interval.start, newInterval.start)
                newInterval.end = max(interval.end, newInterval.end)
        results.insert(insertPos, newInterval)
        return results
#主函数
if __name__ == '__main__':
solution = Solution()
    interval1 = Interval(1,2)
    interval2 = Interval(5,9)
    interval3 = Interval(2,5)
    results = solution.insert([interval1,interval2], interval3)
    print("输入:[",interval1.get(),",", interval2.get(),"]","", interval3.get())
    print("输出:[", results[0].get(), "]")

【例102】N皇后问题 难度等级★★
3.代码实现

class Solution:
    #参数n: 皇后的数量
    #返回值: 不同解的总数
    total = 0
    n = 0
    def attack(self, row, col):
        for c, r in self.cols.items():
            if c - r == col - row or c + r == col + row:
                return True
        return False
    def search(self, row):
        if row == self.n:
            self.total += 1
            return
        for col in range(self.n):
            if col in self.cols:
                continue
            if self.attack(row, col):
                continue
            self.cols[col] = row
            self.search(row + 1)
            del self.cols[col]
    def totalNQueens(self, n):
        self.n = n
        self.cols = {}
        self.search(0)
        return self.total
#主函数
if __name__ == '__main__':
    solution = Solution()
    solution.totalNQueens(4)
    print("输入:", solution.n)
    print("输出:", solution.total)

【例103】主元素 难度等级★★
3.代码实现

class Solution:
    #参数nums: 整数数组
    #返回值: 主元素
    def majorityNumber(self, nums):
        nums.sort()
        i=0;j=0
        while i<=len(nums):
            j=nums.count(nums[i])
            if j>len(nums)//3:
                return nums[i]
            i+=j
        return
#主函数
if __name__ == '__main__':
    solution = Solution()
    nums = [99,2,99,2,99,3,3]
    n = solution.majorityNumber(nums)
    print("输入:", "[99,2,99,2,99,3,3]")
    print("输出:", n)

【例104】字符大小写排序 难度等级★★
3.代码实现

class Solution:
    #参数chars: 需要排序的字母数组
    def sortLetters(self, chars):
        chars.sort(key=lambda c: c.isupper())
#主函数
if __name__ == '__main__':
    solution = Solution()
    str1 = "abAcD"
    arr = list(str1)
    solution.sortLetters(arr)
    print("输入:", str1)
    print("输出:", ''.join(arr))

【例105】上一个排列 难度等级★★
3.代码实现

class Solution:
    #参数num:  整数列表
    #参数: 整数列表
    def previousPermuation(self, num):
        for i in range(len(num)-2, -1, -1):
            if num[i] > num[i+1]:
                break
        else:
            num.reverse()
            return num
        for j in range(len(num)-1, i, -1):
            if num[j] < num[i]:
                num[i], num[j] = num[j], num[i]
                break
        for j in range(0, (len(num) - i)//2):
            num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1]
        return num
#主函数
if __name__ == '__main__':
    solution = Solution()
    num = [1,3,2,3]
    num1 = solution.previousPermuation(num)
    print("输入:", "[1,3,2,3]")
    print("输出:", num1)

【例106】下一个排列 难度等级★★
3.代码实现

class Solution:
    #参数num: 整数列表
    #返回值: 整数列表
    def nextPermutation(self, num):
        for i in range(len(num)-2, -1, -1):
            if num[i] < num[i+1]:
                break
        else:
            num.reverse()
            return num
        for j in range(len(num)-1, i, -1):
            if num[j] > num[i]:
                num[i], num[j] = num[j], num[i]
                break
        for j in range(0, (len(num) - i)//2):
            num[i+j+1], num[len(num)-j-1] = num[len(num)-j-1], num[i+j+1]
        return num
#主函数
if __name__ == '__main__':
    solution = Solution()
    num = [1,3,2,3]
    num1 = solution.nextPermutation(num)
    print("输入:", "[1, 3, 2, 3]")
    print("输出:", num1)

【例107】二叉树的层次遍历 难度等级★★
3.代码实现

class TreeNode:  
     def __init__(self, val=None, left=None, right=None):
         self.val=val  
         self.left=left    #左子树
         self.right=right  #右子树
class Solution:
    #参数root: 二叉树的根
    #返回值:从底向上的层次序遍历
    def levelOrderBottom(self, root):
        self.results = []
        if not root:
            return self.results
        q = [root]
        while q:
            new_q = []
            self.results.append([n.val for n in q])
            for node in q:
                if node.left:
                    new_q.append(node.left)
                if node.right:
                    new_q.append(node.right)
            q = new_q
        return list(reversed(self.results))
#主函数
if __name__ == '__main__':
    solution = Solution()
    root=TreeNode(1,TreeNode(2),TreeNode(3))
    results = solution.levelOrderBottom(root)
    print("输入: {1,2,3}")
    print("输出:", results)

【例108】最长公共子串 难度等级★★
3.代码实现

class Solution:
    #参数A, B: 两个字符串
    #返回值: 最长公共子串的长度
    def longestCommonSubstring(self, A, B):
        ans = 0
        for i in range(len(A)):
            for j in range(len(B)):
                l = 0
                while i + l < len(A) and j + l < len(B) \\
                    and A[i + l] == B[j + l]:
                    l += 1
                if l > ans:
                    ans = l
        return ans
#主函数
if __name__ == '__main__':
    solution = Solution()
    A = "ABCD"
    B = "CBCE"
    ans = solution.longestCommonSubstring(A, B)
    print("输入:","A =",A,"B =",B)
    print("输出:", ans)

【例109】最近公共祖先 难度等级★★
3.代码实现

#Definition of TreeNode:
class TreeNode:  
     def __init__(self, val=None, left=None, right=None):
         self.val=val  
         self.left=left    #左子树
         self.right=right  #右子树
        
class Solution:
    #参数root: 二叉搜索树的根
    #参数A: 二叉树的一个节点
    #参数B: 二叉树的一个节点
    #返回值: 返回两个节点的最低公共祖先(LCA)
    def lowestCommonAncestor(self, root, A, B):
        # A且其下面有B => A
        # B且其下面有A => B
        # A且其下面啥都没有 => A
        # B且其下面啥都有 => B
        if root is None:
            return None
        if root == A or root == B:
            return root
        left_result = self.lowestCommonAncestor(root.left, A, B)
        right_result = self.lowestCommonAncestor(root.right, A, B)
        # A 和 B 一边一个
        if left_result and right_result: 
            return root
        # 左子树有一个点或者左子树有LCA
        if left_result:
            return left_result
        # 右子树有一个点或者右子树有LCA
        if right_result:
            return right_result
        # 左右子树啥都没有
        return None
#主函数
if __name__ == '__main__':
    tree = TreeNode(4, TreeNode(3), TreeNode(7, TreeNode(5), TreeNode(6)))
    solution = Solution()
    result = solution.lowestCommonAncestor(tree, tree.left, tree.right.left)
    print("输入:{4,3,7,#,#,5,6},  LCA(3,5)")
    print("输出:", result.val)

【例110】k数和 难度等级★★
3.代码实现

class Solution:
    def kSumII(self, A, k, target):
        anslist = []
        self.dfs(A, k, target, 0, [], anslist)
        return anslist
    def dfs(self, A, k, target, index, onelist, anslist):
        if target == 0 and k == 0:
            anslist.append(onelist)
            return
        if len(A) == index or target < 0 or k < 0:
            return
        self.dfs(A, k, target, index + 1, onelist, anslist)
        self.dfs(A, k - 1, target - A[index],  index + 1 , onelist + [A[index]], anslist)
#主函数
if __name__ == '__main__':
    solution = Solution()
    A = [1,2,3,4]
    k = 2
    target = 5
    anslist = solution.kSumII(A, k, target)
    print("输入:A = [1,2,3,4]   k = 2   target = 5")
    print("输出:", anslist)

【例111】有序链表转换为二分查找树 难度等级★★
3.代码实现

#定义链表节点
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
#定义树节点
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
class Solution:
    #参数head: 链表的第一个节点
    #返回值: 树节点
    def sortedListToBST(self, head):
        num_list = []
        while head:
            num_list.append(head.val)
            head = head.next
        return self.create(num_list, 0, len(num_list) - 1)
    def create(self, nums, start, end):
        if start > end:
            return None
        if start == end:
            return TreeNode(nums[start])
        root = TreeNode(nums[(start + end) // 2])
        root.left = self.create(nums, start, (start + end) // 2 - 1) #注意是-1
        root.right = self.create(nums, (start + end) // 2 + 1, end)
        return root
#主函数
if __name__ == '__main__':
    solution = Solution()
    listnode = ListNode(1, ListNode(2, ListNode(3)))
    root = solution.sortedListToBST(listnode)
    print(python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

python3的各种经典案例,总共299个案例,直接可以运行(前:100个案例)

python3的各种经典案例,总共299个案例,直接可以运行(后:99个案例)

python3的各种经典案例,总共299个案例,直接可以运行(中:100个案例)

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)