编辑
2025-07-19
算法
00

目录

背景
列表
字符串
集合
字符
string库
map方法
zip方法
itertools
collections
时间间隔及交集
最大公约数
最小公倍数
素数
整数数位操作技巧 // %
排序

背景

很多算法简单等级的题目,不需要比较复杂的思路,直接就可以正常思路解决(常见于日常编码逻辑固化后),这里只需要知道常规的高频使用的点即可(默认Python3刷题)

列表

bash
# 删除某个值 >>> lst = [1,2,3] >>> lst.remove(2) >>> lst [1, 3] # 逆向遍历 for j in range(n - 1, 0, -1): print(j) #这种情况没有遍历到下标为 0 的元素,这是一个常见的 range() 使用误区 # 正确使用:Python 的 range(start, stop, step) 是左闭右开的 for j in range(n - 1, -1, -1):

字符串

bash
# 前后缀判断 prefix suffix >>> 'abab'.startswith('ab') True >>> 'abab'.endswith('ab') True # 纯数字、纯字母、纯数字和字母组合 >> '11'.isdigit() True >>> >>> 'a1'.isalnum() True >>> >>> 'aa'.isalpha() True # join()用法, 序列中的元素连接成一个字符串 '连接符'.join(可迭代对象) >>> '-'.join(['a', 'b', 'c']) 'a-b-c' >>> ''.join(['a', 'b', 'c']) 'abc' # 所有子串 >> s = "10101" >>> [s[i:j] for i in range(len(s)) for j in range(i+1, len(s) + 1)] ['1', '10', '101', '1010', '10101', '0', '01', '010', '0101', '1', '10', '101', '0', '01', '1']

集合

bash
>>> {'a', 'b'} in {'a', 'b'} # 注意!!! 集合 {'b', 'a'} 是否是集合 {'b', 'a'} 的一个元素,这个是不能直接这么用 False >>> {'a', 'b'}.issubset({'a', 'b'}) True >>> {'a', 'b'}.issubset({'b', 'a'}) # 集合是没有顺序的概念 True

字符

字符运算及转换

bash
>>> ord('a') 97 >>> chr(97) 'a' >>> ord('a') - ord('A') 32

string库

string 是一个内置标准库

字符范围判断

bash
>>> import string >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' >>> >>> string.ascii_uppercase

map方法

map() 是一个内置函数,非原地修改。 将一个函数作用到可迭代对象的每个元素上,并返回一个新的迭代器(map 对象)

map(function, iterable)

bash
>> def func(x: int) -> int: ... return x + x ... >>> new_lst = map(func, lst) >>> >>> new_lst <map object at 0x7035210a0910> >>> list(new_lst) [2, 4, 6]

zip方法

Python 的一个内置函数,用来将多个可迭代对象“打包”成一个个元组,返回一个可迭代对象(zip 对象)

bash
>>> a = [1, 2, 3] ... b = ['a', 'b', 'c'] ... ... z = zip(a, b) ... print(list(z)) # 转成列表查看结果 ... [(1, 'a'), (2, 'b'), (3, 'c')] # 高频用法 >>> list(zip(a, a[1:])) [(1, 2), (2, 3)]

itertools

迭代器函数工具集,用于高效地操作可迭代对象,常用于遍历、组合、过滤

bash
# 特定组合全排列 >>> import itertools >>> itertools.permutations('ABC') <itertools.permutations object at 0x72613a04d080> >>> list(itertools.permutations('ABC')) [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')] >>> list(itertools.permutations([1,2,3])) [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] # 三选二 >>> list(itertools.combinations([1,2,3], 2)) [(1, 2), (1, 3), (2, 3)] # 笛卡尔积 >>> list(itertools.product('ABCD', '123')) [('A', '1'), ('A', '2'), ('A', '3'), ('B', '1'), ('B', '2'), ('B', '3'), ('C', '1'), ('C', '2'), ('C', '3'), ('D', '1'), ('D', '2'), ('D', '3')]

collections

高级容器数据类型库,快速计数,队列,默认值字典等等

bash
# 快速统计,不用自己写字典了,刷算法题时很有用 >>> from collections import Counter ... >>> words = ['aa', 'bb', 'aa', 'a', 'b', 'bb'] >>> Counter(words) Counter({'aa': 2, 'bb': 2, 'a': 1, 'b': 1}) >>> Counter(words).most_common(3) #前3复合情况 [('aa', 2), ('bb', 2), ('a', 1)] >>> from collections import defaultdict ... >>> dd = defaultdict(int) ... >>> dd defaultdict(<class 'int'>, {}) >>> >>> dd['a'] += 1 ... >>> >>> dd defaultdict(<class 'int'>, {'a': 1})

时间间隔及交集

datetime 是Python 内置的处理日期和时间的标准库模块

bash
# 字符串转日期 >>> fmt = "%m-%d" >>> datetime.strptime('08-10', fmt) datetime.datetime(1900, 8, 10, 0, 0) # 日期转字符串 >>> datetime.strptime('08-10', fmt).strftime('%Y-%m-%d') '1900-08-10' # 判断两个日期区间是否存在交集 # 字符串转日期对象 fmt = "%Y-%m-%d" s1, e1 = datetime.strptime(start1, fmt), datetime.strptime(end1, fmt) s2, e2 = datetime.strptime(start2, fmt), datetime.strptime(end2, fmt) # 计算交集 start = max(s1, s2) end = min(e1, e2) # 判断是否有交集 if start <= end: return start.strftime(fmt), end.strftime(fmt) else: return None # 无交集 # 交集天数 (end-start).days + 1

最大公约数

bash
>>> def gcd(x: int, y: int) -> int: ... """最大公约数""" ... while y % x != 0: ... x,y = y%x, x ... return x ... >>> gcd(10, 30) 10 >>> >>> gcd(15, 5) 5

最小公倍数

bash
>>> def lcm(x: int, y: int) -> int: ... """最小公倍数""" ... return x * y // gcd(x, y) ... >>> lcm(15, 20) 60

素数

bash
>>> def is_prime(num: int) -> bool: ... """判断一个数是否为素数""" ... for i in range(2, int(num ** 0.5)+1): ... if num % i == 0: ... return False ... return True ... >>> is_prime(5) True

整数数位操作技巧 // %

bash
# 整数反转 >>> num 1357 >>> while num > 0: ... reversed_num = reversed_num * 10 +num % 10 ... num //= 10 ... >>> reversed_num 7531

排序

注意:sorted()为非原地,.sort()为列表专属的原地排序!!!

bash
# 原地排序 >>> lst = [1,5,3] >>> lst.sort() >>> lst [1, 3, 5] # 非原地排序 >>> result = {1: 2, 3: 4, 5: 3} >>> sorted(result) [1, 3, 5] >>> result {1: 2, 3: 4, 5: 3} # 根据字典的value值排序 >>> sorted(result, key=lambda x: result[x]) [1, 5, 3]

本文作者:lixf6

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!