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

Posted cui_yonghua

tags:

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

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

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

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

【例201】多米诺和三格骨牌铺瓦问题 难度等级★★
3.代码实现

class Solution:
    #参数N为整数
    #返回整数
    def numTilings(self, N):
        if N < 3:
            return N
        MOD = 1000000007
        f = [[0, 0, 0] for i in range(N + 1)]
        f[0][0] = f[1][0] = f[1][1] = f[1][2] = 1
        for i in range(2, N + 1):
            f[i][0] = (f[i - 1][0] + f[i - 2][0] + f[i - 2][1] + f[i - 2][2]) % MOD;
            f[i][1] = (f[i - 1][0] + f[i - 1][2]) % MOD;
            f[i][2] = (f[i - 1][0] + f[i - 1][1]) % MOD;
        return f[N][0]
if __name__ == '__main__':
    solution=Solution()
    inputnum=3
    print("输入为:",inputnum)
    print("输出为:",solution.numTilings(inputnum))

【例202】逃离幽灵 难度等级★★
3.代码实现

class Solution:
    #参数ghosts为数组
    #参数target为数组
    #返回布尔类型
    def escapeGhosts(self, ghosts, target):
        target_dist = abs(target[0]) + abs(target[1])
        for r, c in ghosts:
            ghost_target = abs(target[0] - r) + abs(target[1] - c)
            if ghost_target <= target_dist:
                return False
        return True
if __name__ == '__main__':
    solution=Solution()
    inputnum1=[[1, 0], [0, 3]]
    inputnum2=[0, 1]
    print("输入幽灵为:",inputnum1)
    print("输入目标为:",inputnum2)
    print("输出为:",solution.escapeGhosts(inputnum1,inputnum2))

【例203】寻找最便宜的航行旅途(最多经过k个中转站)难度等级★★
1.问题描述
有n个城市由航班连接,每个航班 (u,v,w)表示从城市u出发,到达城市v,价格为w。给定城市数目n,所有的航班flights。找到从起点src到终点站dst线路最便宜的价格,而旅途中最多只能中转K次。如果没有找到合适的线路,返回-1。
2.问题示例
输入n = 3,flights = [[0,1,100],[1,2,100],[0,2,500]],src = 0,dst = 2,K = 0,输出500,即不中转的条件下,最便宜的价格为500。
3.代码实现

import sys
class Solution:
    #参数n为整数
    #参数flights为矩阵
    #参数src为整数
    #参数dst为整数
    #参数K为整数
    #返回整数
    def findCheapestPrice(self, n, flights, src, dst, K):
        distance = [sys.maxsize for i in range(n)]
        distance[src] = 0
        for i in range(0, K + 1):
            dN = list(distance)
            for u, v, c in flights:
                dN[v] = min(dN[v], distance[u] + c)
            distance = dN
        if distance[dst] != sys.maxsize:
            return distance[dst]
        else:
            return -1
if __name__ == '__main__':
    solution=Solution()
    n=3
    flights=[[0, 1, 100], [1, 2, 100], [0, 2, 500]]
    src=0
    dst=2
    K=0
    print("输入城市为:",n)
    print("输入航班为:",flights)
    print("输入出发地:",src)
    print("输入目的地:",dst)
    print("输入中转数:",K)
    print("输出价格为:",solution.findCheapestPrice(n, flights, src, dst, K))

4.运行结果
输入城市为:3
输入航班为:[[0, 1, 100], [1, 2, 100], [0, 2, 500]]
输入出发地:0
输入目的地:2
输入中转数:0
输出价格为:500
【例204】图是否可以被二分 难度等级★★
3.代码实现

class Solution:
    #参数graph为无向图
    #返回布尔类型
    def isBipartite(self, graph):
        n = len(graph)
        self.color = [0] * n
        for i in range(n):
            if self.color[i] == 0 and not self.colored(i, graph, 1):
                return False
        return True
    def colored(self, now, graph, c):
        self.color[now] = c
        for nxt in graph[now]:
            if self.color[nxt] == 0 and not self.colored(nxt, graph, -c):
                return False
            elif self.color[nxt] == self.color[now]:
                return False
        return True
if __name__ == '__main__':
    solution=Solution()
    inputnum=[[1,3],[0,2],[1,3],[0,2]]
    print("输入为:",inputnum)
    print("输出为:",solution.isBipartite(inputnum))

4.运行结果
输入为:[[1, 3], [0, 2], [1, 3], [0, 2]]
输出为:True
【例205】森林中的兔子 难度等级★★
3.代码实现

import math
class Solution:
    #参数answers为数组
    #返回整数
    def numRabbits(self, answers):
        hsh = {}
        for i in answers:
            if i + 1 in hsh:
                hsh[i + 1] += 1
            else:
                hsh[i + 1] = 1
        ans = 0
        for i in hsh:
            ans += math.ceil(hsh[i] / i) * i
        return ans
if __name__ == '__main__':
    solution=Solution()
    inputnum=[1,1,2]
    print("输入为:",inputnum)
    print("输出为:",solution.numRabbits(inputnum))

4.运行结果
输入为:[1, 1, 2]
输出为:5

【例206】最大分块排序 难度等级★★
3.代码实现

class Solution(object):
    def maxChunksToSorted(self, arr):
        def dfs(cur, localmax):
            visited[cur] = True
            localmax = max(localmax, cur)
            if not visited[arr[cur]]:
                return dfs(arr[cur], localmax)
            return localmax
        visited = [False] * len(arr)
        count = 0
        i = 0
        while i < len(arr):
            localmax = dfs(i, -1)
            i += 1
            while i < localmax + 1:
                if not visited[i]:
                    localmax = dfs(i, localmax)
                i += 1
            count += 1
        return count
if __name__ == '__main__':
    solution=Solution()
    arr = [1,0,2,3,4]
    print("输入为:",arr)
    print("输出为:",solution.maxChunksToSorted(arr))

4.运行结果
输入为:[1, 0, 2, 3, 4]
输出为:4
【例207】分割标签 难度等级★★
3.代码实现

class Solution(object):
    def partitionLabels(self, S):
        last = {c: i for i, c in enumerate(S)}
        right = left = 0
        ans = []
        for i, c in enumerate(S):
            right = max(right, last[c])
            if i == right:
                ans.append(i - left + 1)
                left = i + 1
        return ans
if __name__ == '__main__':
    solution=Solution()
    s = "ababcbacadefegdehijhklij"
    print("输入为:",s)
    print("输出为:",solution.partitionLabels(s))

4.运行结果
输入为:ababcbacadefegdehijhklij
输出为:[9, 7, 8]
【例208】网络延迟时间 难度等级★★
3.代码实现

class Solution:
    #参数times为数组
    #参数N为整数
    #参数K为整数
    #返回整数
    def networkDelayTime(self, times, N, K):
        INF = 0x3f3f3f3f
        G = [[INF for i in range(N + 1)] for j in range(N + 1)]
        for i in range(1, N + 1):
            G[i][i] = 0
        for i in range(0, len(times)):
            G[times[i][0]][times[i][1]] = times[i][2]
        dis = G[K][:]
        vis = [0] * (N + 1)
        for i in range(0, N - 1):
            Mini = INF
            p = K
            for j in range(1, N + 1):
                if vis[j] == 0 and dis[j] < Mini:
                    Mini = dis[j]
                    p = j
            vis[p] = 1
            for j in range(1, N + 1):
                if vis[j] == 0 and dis[j] > dis[p] + G[p][j]:
                    dis[j] = dis[p] + G[p][j]
        ans = 0
        for i in range(1, N + 1):
            ans = max(ans, dis[i])
        if ans == INF:
            return -1
        return ans
if __name__ == '__main__':
    solution=Solution()
    times=[[2,1,1],[2,3,1],[3,4,1]]
    N=4
    K=2
    print("时间矩阵为:",times)
    print("网络大小为:",N)
    print("起始节点为:",K)
    print("最小花费为:",solution.networkDelayTime(times,N,K))

【例209】洪水填充 难度等级★★
3.代码实现

class Solution(object):
    def floodFill(self, image, sr, sc, newColor):
        rows, cols, orig_color = len(image), len(image[0]), image[sr][sc]
        def traverse(row, col):
            if (not (0 <= row < rows and 0 <= col < cols)) or image[row][col] != orig_color:
                return
            image[row][col] = newColor
            [traverse(row + x, col + y) for (x, y) in ((0, 1), (1, 0), (0, -1), (-1, 0))]
        if orig_color != newColor:
            traverse(sr, sc)
        return image
if __name__ == '__main__':
    solution=Solution()
    image = [[1,1,1],[1,1,0],[1,0,1]]
    sr = 1
    sc = 1
    newColor = 2
    print("输入图像为:",image)
    print("输入坐标为: [",sr,",",sc,"]")
    print("输入颜色为:",newColor)
    print("输出图像为:",(solution.floodFill(image,sr,sc,newColor)))

【例210】映射配对之和 难度等级★★
3.代码实现

class TrieNode:
    def __init__(self):
        self.son = {}
        self.val = 0
class Trie:
    root = TrieNode()
    def insert(self, s, val):
        cur = self.root
        for i in range(0, len(s)):
            if s[i] not in cur.son:
                cur.son[s[i]] = TrieNode()
            cur = cur.son[s[i]]
            cur.val += val
    def find(self, s):
        cur = self.root
        for i in range(0, len(s)):
            if s[i] not in cur.son:
                return 0
            cur = cur.son[s[i]]
        return cur.val
class MapSum:
    def __init__(self):
        self.d = {}
        self.trie = Trie()
    def insert(self, key, val):
        

以上是关于python3的各种经典案例,总共299个案例,直接可以运行(后:99个案例)的主要内容,如果未能解决你的问题,请参考以下文章

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

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

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

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

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

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