文章目录
一、基础知识
1.基本输入输出
num1 = input() # 返回一个字符串
num2 = int(input()) # 将字符串转为整型
a, b, c = map(int, input().split()) # 一行输入多个数字,并以空格分开
lst1 = list(map(int, input().split())) # 一行输入多个数字,并以空格分开,返回一个列表
print(num1)
print(num2)
print(a,b,c)
print(lst1)
# 输入
12
45
12 23 34
56 66 77
# 输出
12
45
12 23 34
[56, 66, 77]
2.字符列表连接
lst2 = ['hello', 'world']
print(''.join(lst2))
# 输出
helloworld
3.字母的大小写转换
str1 = 'hello'
str2 = 'WORLD'
print(str1)
print(str1.upper())
print(str2)
print(str2.lower())
# 输出
hello
HELLO
WORLD
world
4.匿名函数lambda
def square(a):
return a * a
print(list(map(square, [1, 2, 3])))
print(list(map(lambda x: x*x, [1, 2, 3])))
lst3 = [[2, 4],
[8, 9],
[4, 5],
[5, 10]]
print(sorted(lst3, key=lambda x: x[0]))
# 输出
[1, 4, 9]
[1, 4, 9]
[[2, 4], [4, 5], [5, 10], [8, 9]]
5.进制转换
print(hex(16), oct(16), bin(16))
# 输出
0x10 0o20 0b10000
6.字符与整型之间的转换
print(chr(97), ord('a'))
# 输出
a 97
7.格式化保留小数点后几位小数
num3 = 3.1415926
print(f'{num3:.3f}')
# 输出
3.142
8.列表排序
lst4 = [3, 1, 45, 67, 21]
lst5 = sorted(lst4, reverse=True) # sorted()返回一个新的排序后的列表
print(lst4)
print(lst5)
lst4.sort(reverse=True) # .sort()直接对原来的列表进行重新的排序
print(lst4)
# 输出
[3, 1, 45, 67, 21]
[67, 45, 21, 3, 1]
[67, 45, 21, 3, 1]
二、常用内置模块
1.阶乘factorial
使用阶乘函数求组合数
import math
def c(m, n):
return math.factorial(m)//(math.factorial(n) * math.factorial(m-n))
print(c(5, 2))
print(math.factorial(5))
# 输出
10
120
2.计数器Counter
统计一个列表中各种元素出现的次数
from collections import Counter
lst6 = ['a', 'a', 'c', 'c', 'b']
counter1 = Counter(lst6)
print(counter1)
counter1['a'] += 1;
print(counter1)
print(list(counter1))
print(counter1.keys())
print(counter1.values())
print(counter1.items())
for item in counter1.items():
print(item[0], item[1])
# 输出
Counter({'a': 2, 'c': 2, 'b': 1})
Counter({'a': 3, 'c': 2, 'b': 1})
['a', 'c', 'b']
dict_keys(['a', 'c', 'b'])
dict_values([3, 2, 1])
dict_items([('a', 3), ('c', 2), ('b', 1)])
a 3
c 2
b 1
3.默认字典defaultdict
用哈希表计数的时候,若当前元素不存在,则置为1;但是用defaultdict直接+1就行,不需要判断,因为创建defaultdict的时候已经规定了默认值类型。
from collections import defaultdict
dict1 = defaultdict(int) # 默认为int型,默认值为0
lst7 = ['a', 'a', 'b', 'c', 'c']
for i,x in enumerate(lst7):
dict1[x] += 1
print(dict1)
# 输出
defaultdict(<class 'int'>, {'a': 2, 'b': 1, 'c': 2})
4.双端队列deque
from collections import deque
dq1 = deque([1, 2, 3], maxlen=4) # # 初始化一个最大长度为maxlen的队列
dq1.append(1)
print(dq1)
dq1.append(4)
print(dq1)
dq2 = deque() # 初始化一个无固定长度的队列
dq2.append(2) # 队尾添加元素
dq2.append(3)
dq2.append(1)
dq2.append(6)
dq2.appendleft(0) # 队首添加元素
print(dq2)
print(dq2.popleft(),dq2.pop())
print(dq2)
# 输出
deque([1, 2, 3, 1], maxlen=4)
deque([2, 3, 1, 4], maxlen=4)
deque([0, 2, 3, 1, 6])
0 6
deque([2, 3, 1])
5.全排列permutations
from itertools import permutations
lst8 = list(permutations([1, 2, 3])) # 全排列
print(lst8)
# 输出
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
6.组合combinations
from itertools import combinations
lst9 = list(combinations([1, 2, 3], 2)) # 第二个参数为选择组合的个数
print(lst9)
# 输出
[(1, 2), (1, 3), (2, 3)]
7.累加accumulate
accumulate在求前缀和时很好用
from itertools import accumulate
lst10 = [1, 2, 3, 4.5, 5]
print(list(accumulate(lst10)))
print(list(accumulate(lst10, initial=0))) # 如果提供了关键字参数 initial,则累加会以 initial值开始,这样输出就比输入的可迭代对象多一个元素。
# 输出
[1, 3, 6, 10.5, 15.5]
[0, 1, 3, 6, 10.5, 15.5]
8.堆heapq
python中的堆是小顶堆,如果是二维列表,默认以每个列表的第一个元素来排序。
1)heapify让列表具有堆的特征;
2)heappop弹出最小的元素(总是位于索引0处)
3)heappush用于在堆中添加一个元素;
4)heapreplace从堆中弹出最小的元素,再压入一个新元素
from heapq import *
hpq = [[2, 4], [8, 9], [4, 5], [5, 10]]
heapify(hpq) # 将列表堆化
print(hpq)
print(heappop(hpq)) # 弹出堆顶元素
print(hpq)
heappush(hpq, [1, 10]) # 元素进堆
print(hpq)
print(heapreplace(hpq, [4,6])) # heapreplace()将原堆的堆顶元素弹出,并且将新元素压进堆里
print(hpq)
时间库datetime
from datetime import *
start = date(year=2024, month=2, day=25)
end = date(year=2024, month=2, day=29)
t = timedelta(days=1)
while start <= end:
print(start, start.weekday())
start += t
print(end.year, end.month, end.day)
time1 = '2024-02-25 09:45:30'
time2 = '2024-02-25 11:22:03'
print(type(time1), time1)
time1 = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S') # strptime定一个时间字符串和分析模式,返回一个时间对象。
print(type(time1), time1)
time2 = datetime.strptime(time2, '%Y-%m-%d %H:%M:%S')
deltat = time2 - time1
print(deltat.seconds)
# 输出
2024-02-25 6
2024-02-26 0
2024-02-27 1
2024-02-28 2
2024-02-29 3
2024 2 29
<class 'str'> 2024-02-25 09:45:30
<class 'datetime.datetime'> 2024-02-25 09:45:30
5793
三、常用算法模板
1.最大公因数与最小公倍数
求两个数的最大公因数可以通过math.gcd(n,m)获取,同时也可以定义辗转相除法获取。
m*n = 最大公因数 * 最小公倍数
因此求两个数的最小公倍数可以通过最大公因数求得。
import math
print(math.gcd(3, 6))
def gcd(a, b):
if a < b:
a, b = b, a
while b:
a, b = b, a % b
return a
print(gcd(6, 3))
def lcm(a, b):
return a*b // math.gcd(a,b)
print(lcm(3, 6))
# 输出
3
3
6
2.质数的判断,质数个数的求解
判断一个数是否为质数,可以通过暴力算法求得,而对于求(n, m)范围内,不包括m,质数的个数,可以通过埃氏筛来求取。
埃氏筛原理:一个数为质数,则它的倍数一定不是质数。
def isPrim(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(isPrim(4))
def countPrim(n,m):
flags = [True for i in range(m)]
for i in range(2,m):
if flags[i]:
for j in range(i+i, m, i):
flags[j] = False
count = 0
for i in range(n,m):
if flags[i]:
count += 1
return count
print(countPrim(2,7))
3.快速幂
快速幂,可以有效优化幂次运算的时间效率
def normalPower(base, power):
result = 1
while power:
if power % 2 == 1:
result = result * base
base = base * base
power //= 2
return result
print(normalPower(2,16))
# 输出
65536
4.二分查找与插入
1)查找:
bisect:查找目标元素右侧插入点
bisect_right:查找目标元素右侧插入点
bisect_left:查找目标元素左侧插入点
2)插入:
insort:查找目标元素右侧插入点,并保序地插入元素
insort_right:查找目标元素右侧插入点,并保序地插入元素
insort_left: 查找目标元素左侧插入点,并保序地插入元素
from bisect import *
lst11 = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5]
print(bisect(lst11,3))
print(bisect_right(lst11,3))
print(bisect_left(lst11,3))
insort(lst11,3.5)
print(lst11)
insort_right(lst11,3)
print(lst11)
insort_left(lst11,3)
print(lst11)
# 输出
[1, 2, 2, 3, 3, 3, 3.5, 4, 4, 4, 4, 5]
[1, 2, 2, 3, 3, 3, 3, 3.5, 4, 4, 4, 4, 5]
[1, 2, 2, 3, 3, 3, 3, 3, 3.5, 4, 4, 4, 4, 5]
更新时间
2024.02.25