python_note

global(全局) nonlocal(嵌套函数)

IO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 循环读取到文件末尾
try:
while True:
s = input()
except:
pass

# 读取n,m,再读取n个数,m行
n, m = (int(_) for _ in input().strip().split(" "))
a = [int(_) for _ in input().strip().split(" ")]
for i in range(m):
s = input()

# 读取的第二种方法,map映射
a1 = list(map(int, input().split()))

# 输出n个数在一行(无行尾空格)
ans = [1, 2, 3, 4]
for j in ans[:-1]:
print(j, end=" ")
print(ans[-1])

自定义排序

1
2
3
4
nums.sort(key=lambda x:x[0])

from functools import cmp_to_key
nums.sort(key=cmp_to_key(lambda x,y:x-y)

对于cmp(this,other), 如果返回为负值,则将this元素排列到输出列表前面

1
2
3
4
5
6
def cmp(a, b):
if a + b >= b + a:
return 1
else:
return -1
arr = sorted(arr, key=cmp_to_key(cmp), reverse=True)

enumerate

1
for index,value in enumerate(lst)

排列组合

全组合

1
2
3
4
5
from itertools import combinations
a = 'abc' #对字符串进行combinations排列组合
for i in combinations(a,2):
x = ''.join(i)
print (x,end=' ')

output:ab ac bc

全排列

1
2
3
4
5
6
>>> a=[1,2,3]
>>> result=itertools.permutations(a,2)
>>> type(result)
<class 'itertools.permutations'>
>>> list(result)
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

解包

*list 去除括号

1
2
3
>>> list1 = [1,2,3]
>>> print(*list1)
1 2 3

String

format

  • {a:.2f} 保留a小数点后两位

  • 1
    2
    >>> f"{a:8.1f}"
    ' 123.5'
  • {a:<10d} 左对齐 (宽度为10)

  • {a:0>2d} 数字右对齐,并补零 (宽度为2) e.g. 5 -> 05

进制

b:二进制;o:八进制;d:十进制;x:十六进制

其他进制转十进制

1
int(‘302’, [2/8/16])

十进制转其他进制

1
bin(),oct(),hex()

双向队列

collections.deque([iterable[,maxlen]])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
d = deque('python')    #生成一个新的deque

d.append('r') #右边新增一值
d.appendleft('l') #左边新增一值,list不存在此方法
d.extend(iterable) #右边新增可迭代对象
d.extendleft
d.insert(index,'m')

d.pop() #删掉并返回最右边值
d.popleft() #删掉并返回最左边值

print(d.count('p')) #count计数方法,返回次数
print(d.index('y')) #index定位操作,返回位置

d.reverse
d.clear

但deque不支持切片slice操作

计数器

collections.counter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from collections import Counter

list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"]
dic = Counter(list1)
print(dic)
#结果:次数是从高到低的
#Counter({'a': 3, 'g': 3, 'c': 2, 'f': 2, 'b': 1})

print(dict(dic))
#结果:按字母顺序排序的
#{'a': 3, 'b': 1, 'c': 2, 'f': 2, 'g': 3}

print(dic.items()) #dic.items()获取字典的key和value
#结果:按字母顺序排序的
#dict_items([('a', 3), ('b', 1), ('c', 2), ('f', 2), ('g', 3)])

print(dic.keys())
#结果:
#dict_keys(['a', 'b', 'c', 'f', 'g'])

print(dic.values())
#结果:
#dict_values([3, 1, 2, 2, 3])

最大公约数

math.gcd(*integers)

最小公倍数

math.lcm(*integers)

n!

math.factorial(n)

二分 bisect

  • 前提:列表有序

  • 使用 bisect 模块的方法之前,须确保待操作对象是 有序序列

bisect.bisect_left(array, x, [lo=0, hi=len(a)])

  • 找出插在最靠近x之前的位置,lo/hi上下限

heapq最小堆

import heapq

  1. 创建堆

    • a=[]
    • a=heapify(x) :一个列表转化为小根堆
    1
    2
    heapq.heappush(a,18)
    heappop(a)
  2. nlargest(n , iterbale, key=None) / nsmallest(n , iterbale, key=None)

    获取列表中最大、最小的几个值

    1
    2
    3
    a = [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
    heapq.nlargest(5,a)
    # [25, 20, 15, 10, 8]

数论

  1. 质数

    1
    2
    3
    4
    5
    6
    7
    n = eval(input())
    primes = [1]*n
    primes[0]=primes[1]=0
    for i in range(2,int(n**0.5)+1):
    if primes[i]:
    primes[i*i:n:i]=[0]*((n-i*i-1)//i+1)
    print(sum(primes))
  2. 扩展欧几里得

    • ax+by=gcd(a,b)
    1
    2
    3
    4
    5
    6
    def exgcd(a, b):
    if b == 0:
    return 1, 0, a
    x, y, g = exgcd(b, a % b)
    x, y = y, x - a // b * y
    return x, y, g
image-20240410204638912

快速幂

pow(a,b,z)= a^b%z

IDLE settings

  • *Python

  • 打开目录下的config-extensions.def文件

  • [AutoComplete] enable=1 popupwait=0

  • 找到 AutoComplete.py

  • """Complete either attribute names or file names.
    
    Either on demand or after a user-selected delay after a key character,
    pop up a list of candidates.
    """
    import os
    import string
    import sys

python_note
http://example.com/2024/06/30/python-note/
作者
LSL
发布于
2024年6月30日
许可协议