蓝桥杯 Python B组-代码模板

本专栏主要分享介绍蓝桥杯pythonB组备赛经验,希望可以帮到有需要的同学。


gcd

def gcd(a,b):
    return a if b == 0 else gcd(b, a % b)

lcm

def lcm(a,b):
    return a * b / gcd(a,b)

leapyear

year % 4 == 0 and year % 100 != 0 or year % 400 == 0

floyed

n = 5
g = [[0,2,4,7,0],
     [2,0,1,0,2],
     [4,1,0,1,6],
     [7,0,1,0,0],
     [0,2,6,0,0]]
for k in range(n):  # 无向图 节点个数 = 数组长度
    for i in range(n):
        for j in range(n):
            if g[i][j] > g [i][k] + g[k][j]:
                g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
print(g[0][-1])  # 4

简单dp

# 最小路径和
def minPathSum(li,i,j):
    m = len(li)
    n = len(li[0])
    return dp(li,m - 1, n - 1)
	memo = [[-1 for i in range(m)]for j in range(n)]
    def dp(li,i,j):
        if i == 0 and j == 0:
            return li[i][j]
        if(i < 0 or j < 0):
            return float('inf')
        if memo[i][j] != -1:
            return memo[i][j]
        memo[i][j] = math.min(dp(li,i - 1,j),dp(li,j - 1,i)) + li[i][j]
        return memo[i][j]
    
# 01背包
for i in range(1,m + 1):
    for j in range(1,n + 1):
        dp[i][j] = dp[i - 1][j]
        if j  >= vs[i]:
            dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - vs[i]] + ws[i])

回溯求全排列

li = [1,2,3]
ans = []
def backtrack(st,ed):
  if st == ed:
    ans.append(li[:])
    return
  for i in range(st,ed):
    li[i],li[st] = li[st],li[i]
    backtrack(st + 1,ed)
    li[i],li[st] = li[st],li[i]
    
backtrack(0,len(li))
print(ans)

素数一

import math

def check(n):
    if(n <= 3):
        return n > 1
    if(n % 6 != 1 and n % 6 != 5):
        return False
    for i in range(5,int(math.sqrt(n)) + 1,6):
        if n % i == 0 or n % (i + 2) == 0:
           return False
    return True

for i in range(100):
    if check(i):
        print(i)

素数二

n = 100
ns = [False] * (n + 1)

for i in range(2, n + 1):
    if ns[i]:
        continue
        
    print(i)
    for j in range(i,n//i + 1):
        ns[i * j] = True

二叉树遍历

def traverse(root):
    if not root:
        return
    # 前序遍历
    traverse(root.left)
    # 中序遍历
    traverse(root.right)
    # 后序遍历

并查集

parent=[i for i in range(n)]
def union(p,q):
    parent[find[p]] = find[q]
def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])
    return parent[x];
def isConn(p,q):
    return find(p) == find(q)

位运算技巧

('a' | ' ') = 'a'
('A' | ' ') = 'a'

('b' & '_') = 'B'
('B' & '_') = 'B'

('d' ^ ' ') = 'D'
('D' ^ ' ') = 'd' 

数论

等比数列求和

a 1 ( 1 − q n ) / ( 1 − q ) a1(1-q^n)/(1-q) a1(1qn)/(1q)

等差数列求和

n ( a 1 + a n ) / 2 n(a1+an)/2 n(a1+an)/2

你可能感兴趣的:(蓝桥杯,Python,B组,python,蓝桥杯)