P1000 A+B Problem
print(sum(map(int,input().split())))
P1002 过河卒
n,m,x,y=map(int,input().split())
def c(a,b):return (a==x or b==y or abs(x-a)+abs(y-b)!=3) and not(a<0 or b<0 or (a==x and b==y))
f=[[0]*(m+1)for i in range(n+1)];f[0][0]=1
for i in range(n+1):
for j in range(m+1):f[i][j]+=c(i-1,j)*f[i-1][j];f[i][j]+=c(i,j-1)*f[i][j-1]
print(f[n][m])
P1018 乘积最大
n,k=map(int,input().split());s,f=input(),[[0]*(k+1)for i in range(n+1)]
for i in range(1,n+1):f[i][0]=int(s[:i])
for l in range(1,k+1):
for i in range(l+1,n+1):
for j in range(l,i):f[i][l]=max(f[i][l],f[j][l-1]*int(s[j:i]))
print(f[n][k])
P1044 栈
n=int(input());f=[0]*25;f[1]=1
for i in range(2,n+1):f[i]=f[i-1]*(4*i-2)//(i+1)
print(f[n])
多组数据的简易玩法
exec(int(input())*"a,b=map(int,input().split());print((b-a%b)%b);")
sort/sorted 函数
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
用于返回一个排序的序列
sorted(iterable, key=None, reverse=False)
>>>example_list = [5, 0, 6, 1, 2, 7, 3, 4]
>>> result_list = sorted(example_list, key=lambda x: x*-1)
>>> print(result_list)
[7, 6, 5, 4, 3, 2, 1, 0]
zip 函数
用于将多个序列打包成一个
>>> p=[1,2,3]
>>> q=[1,4,9]
>>> for i in zip(p,q): print(i)
(1, 1)
(2, 4)
(3, 9)
>>> zip(*zip(p,q))
<zip object at 0x0349EC28>
>>> a1,a2=zip(*zip(p,q))
>>> a1
(1, 2, 3)
>>> a2
(1, 4, 9)
>>>
P2249 查找 - 二分查找
I=lambda:map(int,input().split())
n,m=I();a=list(I());b=I()
for t in b:
l,r=0,n-1
while l<r:
mid=(l+r)//2
if a[mid]<t: l=mid+1
else: r=mid
if a[l]==t:print(l+1,end=' ')
else: print(-1,end=' ')
利用字典进行替代
I=lambda:map(int,input().split())
n,m=I();a=list(I());b=I();x={};j=0;
for i in a:
j+=1;
if i not in x:x[i]=j;
for i in b:print(x[i] if i in x else -1,end=' ')
P2708 硬币翻转
从前有很多个硬币摆在一行,有正面朝上的,也有背面朝上的。正面朝上的用1表示,背面朝上的用0表示。现在要求从这行的第一个硬币开始,将前若干个硬币一起翻面,问如果要将所有硬币翻到正面朝上,最少要进行这样的操作多少次?
利用结论,最坏情况下要 \(n\) 次,如果两个相邻相同则省 \(1\) 次,如果最后一个是 \(1\) 的话再省一次
s=input();n=len(s);a=n-(s[n-1]=='1')
for i in range(1,n):a-=s[i]==s[i-1]
print(a)
P1141 01迷宫
有一个仅由数字\(0\)与\(1\)组成的\(n \times n\)格迷宫。若你位于一格0上,那么你可以移动到相邻\(4\)格中的某一格\(1\)上,同样若你位于一格1上,那么你可以移动到相邻\(4\)格中的某一格\(0\)上。
你的任务是:对于给定的迷宫,询问从某一格开始能移动到多少个格子(包含自身)。
写 BFS 使用 List 的 insert 和 pop 即可
n,m=map(int,input().split())
mp=['' for i in range(n+1)]
for i in range(1,n+1): mp[i]=' '+input()
vis=[[0]*(n+1) for i in range(n+1)]
dx=[1,0,-1,0]
dy=[0,1,0,-1]
color=0
ans={}
def bfs(x,y):
qx=[x];qy=[y]
vis[x][y]=color
global count
while qx:
px=qx.pop();py=qy.pop()
count+=1
for i in range(4):
nx=px+dx[i];ny=py+dy[i]
if 1<=nx<=n and 1<=ny<=n and not vis[nx][ny] and mp[px][py]!=mp[nx][ny]:
qx.insert(0,nx)
qy.insert(0,ny)
vis[nx][ny]=color
for i in range(1,n+1):
for j in range(1,n+1):
if not vis[i][j]:
color+=1
count=0
bfs(i,j)
ans[color]=count
for i in range(m):
x,y=map(int,input().split())
print(ans[vis[x][y]])
递归限制设定
默认递归限制很小,利用以下代码设置
import sys
sys.setrecursionlimit(10000)