1.手撕卷积运算
import os import re import sys from typing import List class Solution: def conv2d(self, kernel, image, stride): k_shape = len(kernel) img_shape = len(image) res_size = (img_shape - k_shape) // stride + 1 # print(res_size) res = [[0] * res_size for _ in range(res_size)] row_start = 0 for i in range(res_size): col_start = 0 for j in range(res_size): cut_image = image[row_start:k_shape + row_start] cut_image = [cut_image[k][col_start:col_start + k_shape] for k in range(k_shape)] # print(cut_image) res[i][j] = self.multiplyTwoMatrix(kernel, cut_image) # print(res[i][j]) col_start += stride row_start += stride return res_size, res def multiplyTwoMatrix(self, A: List[List[int]], B: List[List[int]]): n = len(A) res = 0 for i in range(n): for j in range(n): res += A[i][j] * B[i][j] return res if __name__ == "__main__": kernel = input() k_size, k_input = kernel.split(",") k_size = int(k_size[0]) k_nums = list(map(int, k_input.split(" ")[1:])) kernels = [] for i in range(0, len(k_nums), k_size): kernels.append(k_nums[i:i + k_size]) # print(kernels) # print(k_size) image = input() img_size, img_input = image.split(",") img_size = int(img_size[0]) img_nums = list(map(int, img_input.split(" ")[1:])) images = [] for i in range(0, len(img_nums), img_size): images.append(img_nums[i:i + img_size]) # print(images) stride = int(input()) # padding补0 padding_images = [] for _ in range(stride): padding_images.append([0] * (img_size + 2 * stride)) for x in range(img_size): padding_images.append([0] * stride + images[x] + [0] * stride) for _ in range(stride): padding_images.append([0] * (img_size + 2 * stride)) # print(padding_images) sl = Solution() # print(sl.multiplyTwoMatrix([[1, 2], [3, 4]], [[5, 6], [7, 8]])) # print(sl.conv2d(kernels, images, stride)) res_first, res_second = sl.conv2d(kernels, padding_images, stride) ans = [] for a in range(res_first): for b in range(res_first): ans.append(str(res_second[a][b])) print(str(res_first) + " " + str(res_first) + ", " + " ".join(ans))
2.求第三条高的可能值
# 使用的公式 # 三角形两边之和大于第三边 # 三角形两边之差小于第三边 import math class Solution: # return "No Answer" 33% def getThirdHeight(self, x: int, y: int): a, b = max(x, y), min(x, y) if a == b: return "No Answer" # 如果a * b / (a + b)结果和a * b // (a + b)结果相同,说明数学意义上a * b / (a + b)是个整数 if a * b / (a + b) == a * b // (a + b): # start结果加一是因为start在结果中可以取到 start = a * b // (a + b) + 1 else: # 如果a * b / (a + b)结果和a * b // (a + b)结果不同,说明前者肯定大于后者,取上整数 start = int(math.ceil(a * b / (a + b))) # 同理,end结果如果是整数,是不能取到的 if a * b / (a - b) == a * b // (a - b): end = a * b // (a - b) else: # 如果不是整数,取上整 end = int(math.ceil(a * b / (a - b))) res = [] # 结果中均减去1 for i in range(end - 1, start - 1, -1): res.append(i) if not res: return "No Answer" return res if __name__ == "__main__": sl = Solution() X, Y = input().split() X, Y = int(X), int(Y) print(sl.getThirdHeight(X, Y))
第二题的输出给直接整吐了。。。
全部评论
(4) 回帖