Python Algorithm
LeetCode
3270. Find the Key of the Numbers
- You are given three positive integers num1, num2, and num3.
- The key of num1, num2, and num3 is defined as a four-digit number such that:
- Initially, if any number has less than four digits, it is padded with leading zeros.
- The iᵗʰ digit (1 ≤ i ≤ 4) of the key is generated by taking the smallest digit among the iᵗʰ digits of num1, num2, and num3.
- Return the key of the three numbers without leading zeros (if any).
- Constraints
- 1 ≤ num1, num2, num3 ≤ 9999
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
# zip
str_1 = str(num1).zfill(4)
str_2 = str(num2).zfill(4)
str_3 = str(num3).zfill(4)
answer = ""
for chr_1, chr_2, chr_3 in zip(str_1, str_2, str_3):
answer += min(chr_1, chr_2, chr_3)
return int(answer)
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
str1 = str(num1).zfill(4)
str2 = str(num2).zfill(4)
str3 = str(num3).zfill(4)
answer = ""
for i in range(4):
answer += min(str1[i], str2[i], str3[i])
return int(answer)
1572. Matrix Diagonal Sum
- Given a square matrix [mat], return the sum of the matrix diagonals.
- Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
- Constraints
- n == mat.length == mat[i].length
- 1 ≤ n ≤ 100
- 1 ≤ mat[i][j] ≤ 100
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
answer = 0
n = len(mat)
for i in range(n):
answer += mat[i][i]
answer += mat[i][n-1-i]
# 한 변의 길이가 홀수일 때는 겹치는 중간값 한번 빼주기
if n % 2 == 1:
answer -= mat[n//2][n//2]
return answer
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
answer = 0
for i in range(n):
answer += (mat[i][i] + mat[i][-i-1])
if n % 2 != 0:
answer -= mat[n//2][n//2]
return answer
https://leetcode.com/problems/find-the-key-of-the-numbers/
https://leetcode.com/problems/matrix-diagonal-sum/