蓝桥杯python常用代码(最后一周救命的那种)

# 没事做,那就让脑袋知道谁才是主控,毕竟俺最近脑瓜子嗡嗡的……

# 你还在为没有预习python而发愁吗?心动不如行动,希望对你有用!!!

#分享一句俺很喜欢的句子:

        既然命运充满不确定性,不如现在就去做想做的事,去见想见的人!!

  • 1. 简单输入输出(100%):

  1.1 简单输入:

        #用法:在字符串前加f,并用{}包裹变量或表达式;

        #优点:输出速度快,简化变量插入和表达式计算,提升代码可读性

n = int(input())							#输入一个数字
nums = list(map(int, input().split()))		#输入多个数字
s = input().strip()							#输入字符串{去除首尾空格}

  1.2 简单输出:

name = "Genoa"
age = 25
print(f"姓名:{name}, 年龄:{age}")  # 输出:姓名:Genoa, 年龄:25
  • 2. 自定义排序条件{结合列表、字典使用}:

   2.1 条件1升序{适用于列表或字典,不可为空}

key=lambda x: x[0]	

   2.2 条件1升序+条件2降序{适用于字典,不可为空}

key=lambda x: (x[0], -x[1])

  2.3 字符串排序{适用于带有字符串的字典,示例代码为降序} 

key=lambda x: x[::-1] / key=lambda x: -ord(x[0])
  • 3. 列表操作(100%):

  3.1 列表推导式生成1~10的平方

squares = [x**2 for x in range(1,11)]

  3.2  列表切片

arr = [1,2,3,4,5]					
print(arr[:3])    	# 前三位:[1,2,3]
print(arr[-3:])   	# 后三位:[3,4,5]
print(arr[::-1])  	# 列表反转:[5,4,3,2,1]

  3.3 排序{重点}

        3.3.1原列表直接排序:

list_name.sort(key=None, reverse=False)

示例:
nums.sort()             	# 默认为升序排序
nums.sort(reverse=True) 	# 降序排序

       3.3.2. 创建新列表排序,原列表不变:

list_sorted = sorted(list_name, key=None, reverse=False)

示例:
sorted_nums = sorted(nums, reverse=True)  # 创建新列表并按照降序排列

  3.4 补充{自定义排序,使用lambda}

        3.4.1按单词长度升序

words = ["apple", "kiwi", "banana", "pear"]
words.sort(key=lambda x: len(x))  
print(words)  # 输出 ['kiwi', 'pear', 'apple', 'banana']

        3.4.2.不区分大小写排序:

words = ["Apple", "banana", "Cherry", "apricot"]
sorted_words = sorted(words, key=lambda x: x.lower())
print(sorted_words)  # 输出 ['Apple', 'apricot', 'banana', 'Cherry']

3.5 添加/删除元素:

arr.append(6)    	# 末尾加6
arr.pop(0)       	# 删除第一个元素	
  • 4. 字典快速统计:

4.1 特点:

        无序性;key的类型不可变;key唯一,每个key对应一个value.

4.2 创建字典{重点}

dict1 = {"name": "Alice", "age": 25}				#直接创建
dict2 = dict(name="Bob", age=30)					#使用dict()创建
dict3 = dict([("name", "Charlie"), ("age", 35)])	#使用两个列表生成
	
keys = ["a", "b", "c"]			
dict4 = {k: 0 for k in keys}  						#字典推导式{重点}

4.3 访问字典{重点}

person = {"name": "Alice", "age": 25}
		print(person["name"])  # 输出 "Alice"			#通过键访问
		print(person.get("gender", "未知"))				#使用get()方法{可避免KeyError }

补充:
    可使用if判断字典中是否含有目标key

4.4 遍历字典{重点}

for key in person:						# 遍历键
    print(key)			
		
for key, value in person.items():		# 遍历键值对
    print(f"{key}: {value}")

4.5 嵌套字典:

employees = {
    			"emp1": {"name": "Alice", "age": 25},
    			"emp2": {"name": "Bob", "age": 30}
}
print(employees["emp1"]["name"])  # 输出 "Alice"

4.6 补充 {多级排序}

data = [("apple", 3), ("kiwi", 2), ("banana", 3), ("pear", 1)]

# 先按数量升序,再按字母降序
sorted_data = sorted(data, key=lambda x: (x[1], -ord(x[0][0])))

print(sorted_data)  	
# 输出 [('pear', 1), ('kiwi', 2), ('banana', 3), ('apple', 3)]
  • 5. 字符串操作{结合列表&字典}:

5.1 特点:

        字符串创建后无法直接修改

5.2 常见操作:

split()		    分割字符串			"a,b,c".split(",") → ['a', 'b', 'c']
join()			合并列表为字符串		"-".join(["a", "b"]) → "a-b"
strip()		    去首尾空白符			" hi ".strip() → "hi"
replace()		替换子串				"hello".replace("e", "a") → "hallo"
startswith()	检查前缀				"file.txt".startswith("file") → True
endswith()		检查后缀				"image.png".endswith(".png") → True

5.3 统计字符串中某个子字符串的个数:

text       = "goog goog study, day day up."
word_count = len(text.split())			# 单词数量
count      = text.lower().count("goog")		# 特定词出现次数
print(f"总单词数:{word_count}, ' goog'出现次数:{count}")

5.4 统计字符串中某个字符的个数:

total_chars = len(text)
target_char = 'g'
char_count  = text.lower().count(target_char)		#不区分大小写,使用lower()
print(f"总字符数:{total_chars}, '{target_char}'出现次数:{char_count}")

6. 循环/条件(100%){结合字典或列表}:

        注意:缩进,符号的使用{Tab / :}

6.1循环语句{重点}:

        6.1.1.筛选数据{筛选年龄 ≥ 20 and 分数 ≥ 80 的学生}

students = [
    {"name": "Alice", "age": 20, "score": 85},
    {"name": "Bob", "age": 22, "score": 78},
    {"name": "Charlie", "age": 19, "score": 92}
]
selected = []

for student in students:
   	if student["age"] >= 20 and student["score"] >= 80:
        selected.append(student)
print(selected)  
# 输出:[{'name': 'Alice', 'age': 20, 'score': 85}]

        6.1.2.处理数据{统计、替换和标记等}

order = {
    "order_id": "A001",
    "items": [
        {"product": "Book", "price": 30, "quantity": 2},
        {"product": "Pen", "price": 5, "quantity": 5}
    ]
}

#统计订单总金额
total = 0
for item in order["items"]:
    total += item["price"] * item["quantity"]
print(f"总金额:{total}元")  # 输出:总金额:85元

# 将价格 ≥10 的商品标记为“高单价”
for item in order["items"]:
    if item["price"] >= 10:
        item["category"] = "高单价"	#新增键值对
print(order["items"])

# 输出:[{'product': 'Book', 'price': 30, 'quantity': 2, 'category': '高单价'}, ...]

6.2条件语句{常常和循环语句结合使用}

products = [
    {"name": "Book", "price": 30, "stock": 10},
    {"name": "Pen", "price": 5, "stock": 0},
   	{"name": "Notebook", "price": 15, "stock": 5}
]

# 分类商品状态
for product in products:
    if product["stock"] == 0:
        status = "缺货"
    elif product["price"] >= 20:
       	status = "高价商品"
    else:
        status = "正常"
    product["status"] = status

print(products)
# 输出:[
   	{'name': 'Book', 'price': 30, 'stock': 10, 'status': '高价商品'},
   	{'name': 'Pen', 'price': 5, 'stock': 0, 'status': '缺货'},
   	{'name': 'Notebook', 'price': 15, 'stock': 5, 'status': '正常'}
]

补充:
    忽略循环索引使用占位符”_”标识
  • 7. 快速输入函数:

import sys
input = lambda: sys.stdin.readline().strip()

函数:
	sys.stdin.readline()	#从标准输入读取一行内容,包含换行符\n
	strip()				    #删除字符串首尾的空白字符

输出:
	直接替换python函数的内置input函数,可直接调用自定义input();
	输出类型为字符串,需要时使用int(input())转换

特点:
	直接调用底层C库,可快速处理大规模输入

补充:
	若输入的某行为空{\n},strip()返回空字符串,可能导致错误,可添加非空校验。

示例代码:
	s = input()
    if not s:
    print("输入为空!")
		
  • 8. 打开文件指令:

with open(file_path, mode='r', encoding=None) as file_object:
	
输入参数:
		file_path:文件路径{包含绝对路径或相对路径}
		mode:文件打开模式{'r'(读)、'w'(覆盖写)、'a'(追加写)、'b'(二进制模式,如'rb')}
		encoding:文件编码类型{默认为utf-8}
输出参数:
		file_object:将打开的文件赋值给变量file_object
  • 9. 文件读取与简单预处理:

records = [line.strip().split() for line in file.readlines()]
函数:
		file.readlines()	#读取文件所有行,返回字符串列表{包含换行符’\n’}
		line.strip()		#删除字符串首尾的空白字符{换行符、空格、制表符}
		line.split(',')	    #按','分割字符串,返回子列表{空格或制表符则为(空)}

返回:
		类型为嵌套列表		#List[List[str]]

补充信息:
file.read()		    #读取整个文件内容为单个字符串
file.readline()	    #逐行读取,每次返回一行字符串
file.readlines()	#读取所有行,返回字符串列表
  • 10. 冷门救命库

10.1. 二分查找(bisect)

        字符在已排序的列表中快速查找目标值的位置,常用于替代手写二分查找。
        重点关注点:已排序好的列表。

示例代码:
import bisect
arr = [1, 2, 2, 2, 3]
print(bisect.bisect_left(arr, 2))   # 输出1(第一个2的位置)
print(bisect.bisect_right(arr, 2))  # 输出4(最后一个2的下一个位置)

使用场景:
查找元素是否存在、维护动态排序列表

10.2. 排列组合(itertools)

生成排列、组合等数学操作

示例代码:
import itertools
# 全排列(n个元素的所有顺序)
print(list(itertools.permutations([1, 2, 3])))  
# 输出:[(1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1)]

# 组合(n选k的无序集合)
print(list(itertools.combinations([1, 2, 3], 2)))  
# 输出:[(1,2), (1,3), (2,3)]

应用场景:
生成所有可能的密码组合、组合优化问题
  • 11. 纯数学问题:

11.1. 使用场景:

    质数筛法、最大公约数/最小公倍数、快速幂

11.2. 示例代码:

11.2.1. 埃氏筛法(求1~n所有质数)

def sieve(n):
    is_prime = [True]*(n+1)
    for i in range(2, int(n**0.5)+1):
        if is_prime[i]:
            is_prime[i*i:n+1:i] = [False]*len(is_prime[i*i:n+1:i])
    return [i for i in range(2,n+1) if is_prime[i]]

代码测试:
    print(sieve(9)) 	#[2, 3, 5, 7]

11.2.2. 快速幂取模(a^b % mod

def qpow(a, b, mod):
    res = 1
    while b:
        if b&1: res = res * a % mod
        a = a * a % mod
        b >>= 1
    return res

代码测试:
    print(qpow(2, 2, 5)) 	#4	
    print(qpow(2, 2, 4)) 	#0
  • 12. 最长递增子序列:

12.1. 使用场景:

    给出整数数组,返回其最长递增子序列的长度

12.2. 示例代码:

def length_of_LIS_optimized(nums):
    tails = []
    for num in nums:
        idx = bisect.bisect_left(tails, num)
        if idx == len(tails):
            tails.append(num)
        else:
            tails[idx] = num
    return len(tails)

12.3. 拓展类型{选择性记忆}

    最长子序列、最大环形链路长度、二叉树的深度等

12.4. 示例代码:

def longest_increasing_subsequence(nums):
    if not nums:				
        return []
    
    n = len(nums)
   	dp = [1] * n          	# dp[i]: 以 nums[i] 结尾的最长递增子序列长度
    prev = [-1] * n       	# prev[i]: 记录前驱索引
    max_length = 1        	# 全局最长长度
    end_idx = 0           	# 最长子序列的末尾索引
    
    for i in range(n):
        for j in range(i):
            if nums[i] > nums[j] and dp[j] + 1 > dp[i]:
                dp[i] = dp[j] + 1
                prev[i] = j  		# 记录前驱索引
        # 更新最长子序列的末尾索引
        if dp[i] > max_length:
        	   	max_length = dp[i]
            end_idx = i
    # 回溯构建子序列
    sequence = []
    current = end_idx
    while current != -1:
        sequence.append(nums[current])
        current = prev[current]
    sequence.reverse()  # 反转得到正向序列
    return sequence

# 测试代码
    nums = [10, 9, 2, 5, 3, 7, 101, 18]
    print(longest_increasing_subsequence(nums))  
    # 输出:[2, 5, 7, 101]
    {上述代码存在bug,若多组子序列长度一致,只返回第一条,丢弃其余序列}。
  • 13. 动态规划:

13.1. 使用场景:

        给定背包容量和物品列表,求容纳的最大价值

13.2. 示例代码:

def knapsack(weights, values, capacity):
    n = len(weights)
    dp = [0] * (capacity + 1)		# 初始化动态规划数组
    for i in range(n):
       	for j in range(capacity, weights[i]-1, -1):
        	dp[j] = max(dp[j], dp[j - weights[i]] + values[i])
    return dp[capacity]

# 示例:物品重量=[2,3,4], 价值=[15,20,30], 容量=5 → 输出35
print(knapsack([2,3,4], [15,20,30], 5))

13.3. 扩展类型{选择性记忆}:

        可重复选取,获取背包的最大价值

13.4. 示例代码:

def complete_knapsack(weights, values, capacity):
    n = len(weights)
    dp = [0] * (capacity + 1)  
    for i in range(n):
        for j in range(weights[i], capacity + 1):  # 正序更新容量
        	dp[j] = max(dp[j], dp[j - weights[i]] + values[i])
    return dp[capacity]
  • 14. 网格路径规划:

14.1. 使用场景:

        按照输入网格和题目要求,计算最小的路径和{最大:只需把min()改为max()}:

14.2. 示例代码:

def min_path_sum_optimized(grid):
	m, n = len(grid), len(grid[0])
	dp = [0] * n
	dp[0] = grid[0][0]

	# 初始化第一行
	for j in range(1, n):
		dp[j] = dp[j-1] + grid[0][j]
	# 更新其他行
	for i in range(1, m):
		dp[0] += grid[i][0]  # 更新第一列
		for j in range(1, n):
    			dp[j] = min(dp[j], dp[j-1]) + grid[i][j]
	return dp[-1]

测试代码:输出为7:1 + 3 + 1 + 1 + 1 
	grid = [[1,3,1],
			[1,5,1],
			[4,2,1]]
print(min_path_sum_optimized(grid))

14.3. 拓展类型{选择性记忆}

         数据链环路的最小{最大}路径的价值和。 

14.4. 示例代码:

def max_circular_subarray_sum(nums):
	if not nums:
		return 0
	# 计算普通最大子数组和(Kadane算法)
	max_normal = current_max = nums[0]
	for num in nums[1:]:
		current_max = max(num, current_max + num)
		max_normal = max(max_normal, current_max)
	# 计算普通最小子数组和(反向Kadane)
	min_sub = current_min = nums[0]
	total = nums[0]
	for num in nums[1:]:
		current_min = min(num, current_min + num)
		min_sub = min(min_sub, current_min)
		total += num
	# 处理全负数情况
	if total == min_sub:
		return max_normal
# 返回两种情况的最大值
return max(max_normal, total - min_sub)


测试代码:
    print(max_circular_subarray_sum([5, -3, 5]))    	# 输出:10
    print(max_circular_subarray_sum([-3, -2, -3]))  	# 输出:-2
  • 15. 深度优先搜索(DFS):

15.1. 使用场景{可结合路径规划或序列排序}

         穷举所有可能的排列组合,如:​​全排列问题、带限制条件的排列​​、路径搜索问题等

15.2. 核心思路{不用管,看看即可}

         通过递归尝试所有可能的路径,当路径完成时保存结果,否则回退并尝试其他选择

15.3. 代码示例:

def permutations(nums):
	res = []
	def backtrack(start):
		if start == len(nums):
    			res.append(nums.copy())
    		return
		seen = set()  # 避免同一层重复元素
		for i in range(start, len(nums)):
    			if nums[i] in seen:  # 跳过重复元素
        			continue
    			seen.add(nums[i])
    			nums[start], nums[i] = nums[i], nums[start]  # 交换
    			backtrack(start + 1)  # 递归下一层
    			nums[start], nums[i] = nums[i], nums[start]  # 回溯
	backtrack(0)
return res

测试代码:
    print(permutations([1, 2, 3]))  # 输出6种排列
    print(permutations([1, 1, 2]))  # 输出3种排列(自动去重)

16. Ended!!!!

        祝你幸运!!!!good luck!

^_^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值