大一蒟蒻,一只又菜又爱网瘾的棠子
理了一些常用的语法和函数(只是我常用的,可能不全,如果有误希望大佬们纠错补充,orz),常用的各种板子会之后分类不定期发布的,欢迎大佬们锐评!(第一次写博客,请手下留情🙏)
一、经典的快读快写
import sys
input=lambda:sys.stdin.readline().rstrip('\r\n')#快读
print=lambda x:sys.stdout.write(str(x)+'\n')
二、math
数论---一生之敌(bushi)
import math
from functools import reduce
b=[1,2,3]
bb=reduce(math.gcd,b)#b的所有元素的最大公因数
math.gcd(b[0],b[1])#最大公约数
x=8
math.bin(x)#二进制
math.hex()#将数字转换为十六进制字符串
math.oct()#将整数转换成八进制字符串
#oct(int("39",16))#十六进制转八进制 39>>>'71'
math.divmod(a,b)#返回(a//b,a%b)
math.pi#圆周率
math.e#自然对数的底数
math.ceil(x)#向上取整
math.floor(x)#向下取整
math.factorial(x)#阶乘,如果x为负数小数,则返回错误
math.pow(x,y)#x的y次方
math.sqrt(x)#x的平方根
math.log(x)#x的自然对数
math.log10(x)#x的10对数
math.log2(x)#x的2对数
math.log1p(x)#x的自然对数(以e为底)ln(1+x)
math.log(x,y)#x以y为底的对数
math.exp(x)#e的x次方
math.sin(math.pi/2)#正弦90度等于1
math.cos(math.pi/2)#余弦90度等于0
math.tan(math.pi/2)#正切90度等于正无穷
math.degrees(x)#弧度转角度
math.radians(x)#角度转弧度
math.hypot(x,y)#返回两个参数的平方和的平方根,即(x,y)到原点的距离
math.sin(x)#正弦
math.cos(x)#余弦
math.tan(x)#正切
math.asin(x)#反正弦
math.acos(x)#反余弦
math.atan(x)#反正切
math.atan2(x,y)#反正切
a = math.inf
a = float('inf')#极大值
三、字符串(😍)
s = "hello world"
w=s.split()#按照指定字符将字符串拆分成序列,默认为空格
print(w)#['hello', 'world']
w=w.strip()#将字符串开头和末尾的空白删除
new_s = s.replace("world", "python") # 将字符串中的 "world" 替换成 "python"(---秒杀maoniang---)
# str.replace(指定字符,目标字符,不超过的次数(可省略))
print(new_s) #hello python
s.swapcase() #将字符串中所有字母的大小写都反转
s.upper() #将字符串所有的字母都转换为大写
s.lower() #将字符串所有的字母都转换为小写
s.isdigit() #检查字符串中的字符是否都是数字
s.isnumeric() #检查字符串中的所有字符是否都是数字字符
s.capitalize() #返回字符串的副本,但将第一个字符大写
s.isalpha() #检查字符串中的所有字符是否都是字母
s.isalnum() #检查字符串中的字符是否都是字母或数
s.isspace() #检查字符串中的字符是否都是空白字符
s.islower() #检查字符串中的所有字母都是小写的
s.isupper() #检查字符串中的所有字母都是大写的
s.istitle() #检查字符串中位于非字母后面的字母都是大写的,且其他所有字母都是小写的/可以检测字符串首字母是否为大写
四、七零八落的数组
a = [int(x) for x in input().split()]
a=list(map(int,input().split()))#经典输入
my_list = [(1, 5, 3), (3, 2, 1), (7, 1, 4), (2, 9, 0)]
sorted_list = sorted(my_list, key=lambda x: x[2])#按列表中的第三个元素对列表进行排序
# 部分逆序
start,end=map(int,input().split())
arr[start:end+1] = arr[start:end+1][::-1]
# def reverse_part_of_array(arr, start, end):
# while start < end:
# arr[start], arr[end] = arr[end], arr[start] # 交换两个元素
# start += 1
# end -= 1
# arr = [1, 2, 3, 4, 5, 6]
# reverse_part_of_array(arr, 1, 4)
# print(arr) # 输出: [1, 5, 4, 3, 2, 6]
arr[start:end+1] = reversed(arr[start:end+1])
#浅复制与深复制
a=[1,2,3]
b=[]
c=[]
b.append(a)#浅
c.append(a[::])#深
arr = [1, 2, 3, 4, 5] # 举例一个包含数字的数组
result = sum(arr[:3]) # 使用切片来获取数组中的前三个元素,并使用 sum 函数求和
b=[6,7,8,9]
arr.extend(b)
print(*arr) #1 2 3 4 5 6 7 8 9
五、格式化
总是为了满足奇葩出题人的需求....
answer=[1,3,5]
print(*answer)#1 3 5
print(f"{answer[1]:.2f}")#3.00
print("%.3f"%(3.45674))#3.457 !!!!!!!!好用
print("%08.3f"%(3.45674))#0003.457
print("a={},b={},c={}".format(*answer))#a=1,b=3,c=5
print("My name is %s and I am %d years old." % (answer[0],answer[1]))#My name is 1 and I am 3 years old.
print(f"My name is {answer[0]} and I am {answer[1]} years old.")#My name is 1 and I am 3 years old.
number = 3.1415926
print("保留两位小数:{:.2f}".format(number))#保留两位小数:3.14
print("保留两位小数:{}".format(round(float(number), 2)))#保留两位小数:3.14
print("保留两位小数:%s" % "%.2f" % number)#保留两位小数:3.14
六、字典dict
w=dict()
print(w)#>>>{}
w.update({'name':'runoob'})
print(w)#>>>{'name': 'runoob'}
w.update({'code':666,'site':'www.runoob.com'})
print(w)#>>>{'name': 'runoob', 'code': 666, 'site': 'www.runoob.com'}
w.pop('code')
print(w)#>>>{'name': 'runoob', 'site': 'www.runoob.com'}
w=dict(zip(['one', 'two', 'three'], [1, 2, 3]))
print(w)#>>>{'one': 1, 'two': 2, 'three': 3}
w=dict([('one', 1), ('two', 2), ('three', 3)])
print(w)#>>>{'one': 1, 'two': 2, 'three': 3}
print(w.items())#>>>dict_items([('one', 1), ('two', 2), ('three', 3)])
print(w.keys())#>>>dict_keys(['one', 'two', 'three'])
print(w.values())#>>>dict_values([1, 2, 3])
arr=[1,5,3,7,2,3,2]
a = sorted(set(arr))#去重升序
d = {}
for i, v in enumerate(a, 1):
d[v] = i
d = sorted(d.items(), key=lambda item:item[1])#字典根据值的大小进行排序
strs=["eat", "tea", "tan", "ate", "nat", "bat"]
res=[]
dic={}
for i in strs:
keys="".join(sorted(i))#!!!!!
if keys not in dic:
dic[keys]=[i]
else:
dic[keys].append(i)
print(list(dic.values()))#[['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
七、各种模块
(常用与顺序无关)
1.statistics模块
import statistics
statistics.mean() #求算术平均值
statistics.median() #计算数据的中位数,如果有两个中位数,则返回其平均值
statistics.median_low() #数据中的低中位数
statistics.median_high() #数据中的高中位数
statistics.mode() #计算众数
statistics.pvariance() #计算数据的总体方差
2.collections
import collections
collections.deque([])
q = collections.deque([1, 2, 3, 4])
q.rotate(1)
print(q) # [4, 1, 2, 3]
q.rotate(1)
print(q) # [3, 4, 1, 2]
from collections import Counter#各个元素计数
a=[1,2,2,1,1,3]
b=Counter(a)
print(b)#Counter({1: 3, 2: 2, 3: 1})
print(b.most_common(1))#[(1, 3)]
b.update([1,2,3,4,5])#更新
print(b)#Counter({1: 4, 2: 3, 3: 2, 4: 1, 5: 1})
count=b[1]
print(count)#4
del b[1]#删除
mm=b.most_common(2)#获取计数最多的前2个元素
print(mm)#[(1, 4), (2, 3)]
al=b.elements()#获取所有元素,返回一个迭代器
b.clear()#清空
print(Counter(a).values())#dict_values([3, 2, 1])
3.datetime、time、calendar
主要针对🏀
import datetime
bt=datetime.date(2000,11,6)
print(bt)#2000-11-06
a=datetime.timedelta(days=100)
b=a+bt#等于b=datetime.date(2001,2,14)
print(b)#2001-02-14
bt.weekday()#返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;
bt.isoweekday()#返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
print(bt.weekday())#0
print(bt.isoweekday())#1
print(bt.isoformat())#标准化'2000-11-06'
print(bt.__format__('%Y/%m/%d'))#'2000/11/06'
import time
date='2024-03-25'
print(time.strptime(date, "%Y-%m-%d")[-2])#85 2024年的第85天
import time
date='2024-03-25'
print(time.strptime(date, "%Y-%m-%d"))
time.struct_time(tm_year=2024, tm_mon=3, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=85, tm_isdst=-1) #'tm_year":年份'tm_mon:月份(1-12)"tm_mday ':一个月中的哪一天(1-31)"tm_hour:小时(O-23)'tm_min":分钟(O-59)'tm_sec':秒(0-59)"tm_wday ":一周中的第几天,从周一开始算起(0-6,0代表周→)’'tm _yday":一年中的第几天(1-366,注意是从1开始的)
#calendar模块
import calendar
calendar.isleap(2022)# False 判断是否为闰年
calendar.leapdays(2000,2020)# 5 返回两年之间的闰年总数v
4.itertools
要是有些题不会超内存就好了🥹
import itertools
for i in itertools.product('ab','cd'):
print(i)
# ('a', 'c')
# ('a', 'd')
# ('b', 'c')
# ('b', 'd')
s='abc'
print(list(itertools.product(s,repeat=2)))#从s中取出两个元素的所有组合,并且最多重复两次
print(list(itertools.permutations('ABC')))
#[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
print(list(itertools.permutations('ABC',2)))
#[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
print(list(itertools.combinations('ABC',2)))#或"ABC"
#[('A', 'B'), ('A', 'C'), ('B', 'C')]
print(list(itertools.accumulate([0,1,0,1,1,2,3,5])))
#[0, 1, 1, 2, 3, 5, 8, 13]前缀和
print(list(itertools.accumulate([0,1,0,1,1,2,3,5],max)))
#[0, 1, 1, 1, 1, 2, 3, 5]可指定函数,max为前i项中的最大值
5.bisect
import bisect
# `bisect` 模块是 Python 标准库中的一个模块,用于实现二分查找算法。它提供了一些函数来在已排序的序列中查找元素的位置,或者向已排序的序列中插入元素并保持排序状态。
bisect.bisect_left(a, x, lo=0, hi=len(a))# 在已排序的列表 `a` 中查找元素 `x` 应该插入的位置,如果有多个相同元素,返回最左侧的位置。可选参数 `lo` 和 `hi` 分别指定搜索的起始和结束位置,默认为列表的开始和结束。
bisect.bisect_right(a, x, lo=0, hi=len(a))# 在已排序的列表 `a` 中查找元素 `x` 应该插入的位置,如果有多个相同元素,返回最右侧的位置。
bisect.bisect(a, x, lo=0, hi=len(a))# `bisect_right` 的别名,通常更常用。
bisect.insort_left(a, x, lo=0, hi=len(a))# 将元素 `x` 插入到已排序的列表 `a` 中,保持排序状态,如果有多个相同元素,插入到最左侧的位置。
bisect.insort_right(a, x, lo=0, hi=len(a))# 将元素 `x` 插入到已排序的列表 `a` 中,保持排序状态,如果有多个相同元素,插入到最右侧的位置。
bisect.insort(a, x, lo=0, hi=len(a))# `insort_right` 的别名,通常更常用。
6.random(嘿嘿)
骗分必备
import random
def a():
return random.randint(0, 9)
b=iter(a,6)
for i in b:
print(i,end=" ")
#生成 0 到 9 之间的随机数,当生成的随机数为 5 时停止迭代。
#这些就够骗分(ioi)了,但是会做的题不建议
八、一些小技巧和注意点,以及奇奇怪怪的新知识
1、动态规划框架(真的好难)
#!!!动态规划
#回溯算法(框架)
ans = []
def trace(path,choices):
if len(path) == len(nums):
ans.append(list(path))
for i in choices:
if i in path:
continue
path.append(i)
trace(path,choices)
path.pop()
return ans
nums = [1,2,3]
print(trace([],nums))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
res=[]
path=[]
def bt(nums,startIndex):
res.append(path[:])
for i in range(startIndex,len(nums)):
path.append(nums[i])
bt(nums,i+1)
path.pop()
nums = [1,2,3]
bt(nums,0)
print(res)
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
2.zip(图论时很好用)
a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
#[(1,4),(2,5),(3,6)]
strs=["flower","flow","flight"]
print(list(zip(*strs)))
#[('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]
matrix = [[3,7,8],[9,11,13],[15,16,17]]
colmin = [i for i in zip(*matrix)]#获取二维数组每列元素
#[(3, 9, 15), (7, 11, 16), (8, 13, 17)]
3、寻找元素(还是它)
a='234523'
#寻找元素时,可以考虑替换 字符串 元素
a=a.replace("3","")
print(a)#'2452'
4、remove/ find/rfind
b=[2,4,6,3,4,2]
b.remove(2)# 删除 列表 中第一个出现的指定值
print(b)#[4, 6, 3, 4, 2]
s='asdfghjkl'
ss='jkl'
print(s.find(ss))#6 find在字符串中查找子串,如果找到,返回字串的第一个字符的索引,找不到返回-1
#字符串.rfind() 查找字符最后一次出现的位置,没有则返回-1
5、额,比较字母?
a = set('qwertyuiop')
b = set("reagdagd")
print(b<a)#False
6、除法!!
# 直线斜率不要用除法,除数可能为0,转用乘法
# y2 / y1 == x2 / x1
# x1 * y2 == x2 * y1
7、根据元素找下标
#可以利用enumerate创建字典后,根据元素找下标
a = sorted(set(arr))
d = {}
for i, v in enumerate(a, 1):
d[v] = i
d = sorted(d.items(), key=lambda item:item[1])#字典根据值的大小进行排序
8、不一般的排序
l = [[5,10],[2,5],[4,7],[3,9]]
l = sorted(l, key=lambda x:-x[1])
#[[5, 10], [3, 9], [4, 7], [2, 5]]按第二个元素降序
l = ["adss","a","sad","sd"]
l = sorted(l,key=lambda x:len(x))
#['a', 'sd', 'sad', 'adss']按元素的长度升序
9、all()
# all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
a=[1,2,3,4,5]
if all(i>0 for i in a):
print("所有元素都大于0")
all(('a', 'b', '', 'd')) #>>>False # 元组tuple,存在一个为空的元素
#元素除了是 0、空、None、False 外都算 True
10、any()
any() #函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
a=[0,1,2,3,4,5]
if any(i>0 for i in a):
print("存在一个元素大于0")
any((0, '', False)) #>>>False # 元组tuple,元素全为0,'',false
any([]) #>>>False# 空列表
11、判断一个对象是否为 str
obj='ABC'
isinstance(obj,str)#>>>True 判断一个对象是否为 str
12、字节代码(某年某题让我知道了它)
eval()!!!!!
str = "for i in range(0,10): print(i)"
c = compile(str,'','exec')
print(c)#<code object <module> at 0x00000200135089C0, file "", line 1>
print(exec(c))
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# None
str = "3 * 4 + 5"
a = compile(str,'','eval')
print(eval(a))#17
# 执行简单的数学表达式
result = eval("2 + 3 * 4")
print(result) # 输出: 14
# 执行变量引用
x = 10
result = eval("x + 5")
print(result) # 输出: 15
# 在指定命名空间中执行表达式
namespace = {'a': 2, 'b': 3}
result = eval("a + b", namespace)
print(result) # 输出: 5
13、复数
#complex() 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。
print(complex(3, 4))#>>>(3+4j)
print(complex(2))#>>>(2+0j)
print(complex('1+2j'))#>>>(1+2j)
14、dir()感觉是万能的记忆magic
dir()#函数:返回当前模块的命名空间中所有名称。
print(dir('a'))#字符串['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(1))#['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
w=[1,2,3]
print(dir(w))#['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
15、global()
globals() #函数会以字典类型返回当前的全局符号表。
That's all! Thanks!!!