classSolution:defjudgePoint24(self, nums: List[int])->bool:
TARGET =24
EPSILON =1e-6
ADD, MULTIPLY, SUBTRACT, DIVIDE =0,1,2,3defsolve(nums: List[float])->bool:ifnot nums:returnFalseiflen(nums)==1:returnabs(nums[0]- TARGET)< EPSILON
for i, x inenumerate(nums):for j, y inenumerate(nums):if i != j:
newNums =list()for k, z inenumerate(nums):if k != i and k != j:
newNums.append(z)for k inrange(4):if k <2and i > j:continueif k == ADD:
newNums.append(x + y)elif k == MULTIPLY:
newNums.append(x * y)elif k == SUBTRACT:
newNums.append(x - y)elif k == DIVIDE:ifabs(y)< EPSILON:continue
newNums.append(x / y)if solve(newNums):returnTrue
newNums.pop()returnFalsereturn solve(nums)
classSolution:defjudgePoint24(self, nums: List[int])->bool:iflen(nums)==1:return math.isclose(nums[0],24)returnany(self.judgePoint24([x]+ rest)for a, b,*rest in itertools.permutations(nums)for x in{a+b, a-b, a*b, b and a/b})
classSolution:defisValid(self, s:str)->bool:# 把一个list当做栈使用
ls =[]
parentheses ="()[]{}"for i inrange(len(s)):
si = s[i]# 如果不是括号则继续if parentheses.find(si)==-1:continue# 左括号入栈if si =='('or si =='['or si =='{':
ls.append(si)continueiflen(ls)==0:returnFalse# 出栈比较是否匹配
p = ls.pop()if(p =='('and si ==')')or(p =='['and si ==']')or(p =='{'and si =='}'):continueelse:returnFalseiflen(ls)>0:returnFalsereturnTrue
import sys
n, m, k =list(map(int,input().split()))
nums =[]
price =[]
weight =[]
va =[]for i inrange(n):
p, w, v =list(map(int,input().split()))
nums.append([p,w,v])
price.append(p)
weight.append(w)
va.append(v)
nums.sort(key=lambda x:(-x[2],x[0],x[1]))
count =0for i inrange(n):if m>=nums[i][1]and k>=nums[i][0]:
m = m - nums[i][1]
k = k - nums[i][0]
count +=1
sys.stdout.write(str(count))
顺时针打印矩阵
classSolution:defprintMatrix(self,matrix):
res =[]while matrix:
res += matrix.pop(0)if matrix:
matrix = self.helpme(matrix)return res
defhelpme(self,matrix):
row =len(matrix)
col =len(matrix[0])
new_mat =[]for i inrange(col):
temp =[]for j inrange(row):
temp.append(matrix[j][col -1-i])
new_mat.append(temp)return new_mat
背包问题
deftrack(d, c, w):# 输出最优路径
x =[]for i inrange(len(w),1,-1):# m[n][c]为最优值,如果m[n][c]=m[n-1][c] ,说明有没有第n件物品都一样if d[i][c]!= d[i -1][c]:
x.append(w[i -1])
c = c - w[i -1]if d[1][c]>0:
x.append(w[0])return x
if __name__ =='__main__':
c =int(input())# 输入一个限制条件,例如背包的体积为c# w = sys.stdin.readline().strip().split(' ') # 每个物品的体积
w =eval(input())# w = list(map(int, w))# v = sys.stdin.readline().strip().split(' ') # 对应每个物体的价值
v =eval(input())# v = list(map(int, v))# w,v = input().split(',')
dp =[[0]*(c +1)for i inrange(len(w)+1)]# 动态规划矩阵for i inrange(1,len(w)+1):for j inrange(1, c +1):if j >= w[i -1]:
dp[i][j]=max(dp[i -1][j], dp[i -1][j - w[i -1]]+ v[i -1])# 动态转移方程else:
dp[i][j]= dp[i -1][j]print(max(dp[len(w)]))# 输出最大值print(track(dp, c, w))# 输出最优路径
回文数
classSolution:defisPalindrome(self, x:int)->bool:if x <0or(x %10==0and x !=0):returnFalse
new =0while x > new:
temp = x %10
x //=10
new = new *10+ temp
if x == new or x == new //10:returnTruereturnFalse