Python 題目37 題

COMBO!

Python 題目 全集

一題一題刷

演算法練習 · 資料結構 · 一題一題刷

二元樹

單篇 ↗
def dfs_pre(T, index):
    n = len(T)
    left = index * 2 + 1
    right = index * 2 + 2
    if T[index] != "null":
        print(T[index], end=" ")
    if left < n:
        dfs_pre(T, left)
    if right < n:
        dfs_pre(T, right)
def dfs_in(T, index):
    n = len(T)
    left = index * 2 + 1
    right = index * 2 + 2
    if left < n:
        dfs_in(T, left)
    if T[index] != "null":
        print(T[index], end=" ")
    if right < n:
        dfs_in(T, right)
def dfs_post(T, index):
    n = len(T)
    left = index * 2 + 1
    right = index * 2 + 2
    if left < n:
        dfs_post(T, left)
    if right < n:
        dfs_post(T, right)
    if T[index] != "null":
        print(T[index], end=" ")

T = input().split()
dfs_pre(T, 0)
print()
dfs_in(T, 0)
print()
dfs_post(T, 0)

使用套件

import bisect

a = [1, 3, 3, 5, 7]
bisect.bisect_left(a, 3)  # 1
bisect.bisect_right(a, 3) # 3

中序式轉後序式(運算)

單篇 ↗
def infix_to_postfix(expression):
    op = {'+': 1,'-':1,'*':2,'/':2}
    stack = []
    output = []

    for char in expression:
        if char.isalnum():
            output.append(char)
        elif char == '(':
            stack.append(char)
        elif char == ')':
            while stack and stack[-1] != '(':
                output.append(stack.pop())
            stack.pop()
        else:
            while(stack and stack[-1] != '(' and op.get(stack[-1],0) >= op.get(char,0)):
                output.append(stack.pop())
            stack.append(char)
    while stack:
        output.append(stack.pop())

    return " ".join(output)

st = input().split()
print(infix_to_postfix(st))

可以使用的import插件

單篇 ↗
# 可以計算字串裡面各有多少個
from typing import Counter
# 可以用來計算排列組合
from itertools import permutations
import math
# 可以使用很多有關字串的東西
import string
temp_upper = string.ascii_uppercase
temp_lower = string.ascii_lowercase
# 可以轉換成分數形式
from fractions import Fraction

string

屬性意義
string.ascii_lowercase'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_letters所有英文字母(大+小寫)
string.digits'0123456789'
string.hexdigits'0123456789abcdefABCDEF'
string.punctuation標點符號(如 !"#$%&'()*+,-./:;<=>?@[]^_)
string.whitespace空白字元:空格、換行、Tab 等

目錄

單篇 ↗

因數分解(Finding Factors)

單篇 ↗
def find_factors(n):
    factors = []
    for i in range(1, int(n ** 0.5) + 1):  # 只需檢查到 sqrt(n)
        if n % i == 0:
            factors.append(i)
            if i != n // i:  # 避免平方數重複
                factors.append(n // i)
    return sorted(factors)

print(find_factors(60))  # 🔹 輸出: [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60]

自訂義進位轉換

單篇 ↗
def to_base(n, base):
    digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if n == 0:
        return "0"
    result = ""
    while n > 0:
        result = digits[n % base] + result
        n //= base
    return result

判斷是不是質數

單篇 ↗
def isPrimeNumber(num):
    if num % 2 == 0:
        return True if num == 2 else False
    for i in range(3,int(num**0.5)+1,2):
        if num%i == 0:
            return False
    else:
        return True

判斷趨勢 + 是否有峰谷

單篇 ↗
def analyze_trend(arr):
    if len(arr) < 3:
        print("趨勢:資料太少")
        return

    # 判斷單調趨勢
    increasing = all(arr[i] <= arr[i+1] for i in range(len(arr)-1))
    decreasing = all(arr[i] >= arr[i+1] for i in range(len(arr)-1))

    if increasing and not all(x == arr[0] for x in arr):
        print("趨勢:遞增")
    elif decreasing and not all(x == arr[0] for x in arr):
        print("趨勢:遞減")
    else:
        print("趨勢:無明顯方向")

    # 判斷山峰與低谷
    peaks = []
    valleys = []

    for i in range(1, len(arr) - 1):
        if arr[i - 1] < arr[i] > arr[i + 1]:
            peaks.append((i, arr[i]))
        elif arr[i - 1] > arr[i] < arr[i + 1]:
            valleys.append((i, arr[i]))

    # 嚴格趨勢條件
    if len(peaks) == 1 and not valleys:
        print(f"嚴格趨勢:有一個山峰 at 位置 {peaks[0][0]},值為 {peaks[0][1]}")
    elif len(valleys) == 1 and not peaks:
        print(f"嚴格趨勢:有一個低谷 at 位置 {valleys[0][0]},值為 {valleys[0][1]}")
    else:
        print("嚴格趨勢:無(山峰/低谷不唯一或混合)")

找到字串裡面的迴文

單篇 ↗
s = input("輸入字串:")
n = len(s)
palindromes = set()

for i in range(n):
    for j in range(i+1, n+1):
        substr = s[i:j]
        if substr == substr[::-1] and len(substr) > 1:
            palindromes.add(substr)

print("所有迴文子字串:", palindromes)

易位質數

單篇 ↗

數字排列組合都符合質數

import sys
input = sys.stdin.readline

MAX = 10 ** 6 + 1

Prime = [True] * MAX
Prime[0] = False
Prime[1] = False

for j in range(2, int(MAX**0.5) + 1):
    if Prime[j]:
        for i in range(j * j, MAX, j):
            Prime[i] = False

from itertools import permutations

def check(T):
    T = str(T)
    for i in permutations(T):
        if not(Prime[int("".join(i))]):
            return False
    return True

c_list = []
for i in range(1, 1000):
    if check(i):
        c_list.append(i)

while True:
    n = int(input())
    if n == 0:
        break
    ans = "0"
    n_len = len(str(n))
    for i in range(n+1, MAX):
        if i * i > MAX:
            break
        if i in c_list and n_len == len(str(i)):
            ans = i
            break
    print(ans)

括號是否有錯誤

單篇 ↗
n = int(input())
for _ in range(n):
    st = input()
    check1 = st.count('(') != st.count(')')
    check2 = st.count('[') != st.count(']')
    if check1 or check2:
        print("No")
    else:
        Ans = "Yes"
        stack = []
        for s in st:
            # 只要 s 是左括號,放到堆疊
            if s in ['(','[']:
                stack.append(s)
            else:
                # 如果s是右括號,就取出堆疊最上方的元素(r)
                # 注意:如果這時候堆疊是空的,代表一定無法匹配,直接輸出No
                # 否則進行比對,是否 ( == ) or [ == ]
                if stack == []:
                    Ans = "No"
                    break
                r = stack.pop()
                if not(r == '(' and s == ')' or r == '[' and s == ']'):
                    Ans = "No"
                    break
        if stack != []:
            Ans = "No"
        print(Ans)

括號深度

單篇 ↗
st = input()
stack = []
max_depth = 0

# 對應的括號
pairs = {')': '(', ']': '[', '}': '{'}

for ch in st:
    if ch in "({[":
        stack.append(ch)
        max_depth = max(max_depth, len(stack))
    elif ch in ")}]":
        if not stack or stack[-1] != pairs[ch]:
            print(-1)
            break
        stack.pop()
else:
    print(max_depth if not stack else -1)

括號深度抓錯誤

單篇 ↗
def check_brackets_full(expr):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    max_depth = 0
    errors = []

    for i, ch in enumerate(expr):
        if ch in pairs.values():  # 開括號
            stack.append((ch, i))  # 儲存 (括號字元, 位置)
            max_depth = max(max_depth, len(stack))
        elif ch in pairs:  # 關括號
            if not stack or stack[-1][0] != pairs[ch]:
                errors.append((i, ch, "多餘或配對錯誤"))
            else:
                stack.pop()

    # 剩下的開括號沒對應右括號
    while stack:
        ch, pos = stack.pop()
        errors.append((pos, ch, "缺少右括號"))

    if errors:
        print(-1)
        for pos, ch, reason in sorted(errors):
            print(f"錯誤:在位置 {pos} 的 '{ch}' → {reason}")
    else:
        print(max_depth)

括號檢測

單篇 ↗
def is_valid_parentheses(s):
    stack = []
    mapping = {")": "(", "]": "[", "}": "{"}
    
    for char in s:
        if char in mapping.values(): # 左括號
            stack.append(char)
        elif char in mapping: # 右括號
            if not stack or stack.pop() != mapping[char]:
                return False
    
    return len(stack) == 0

計算元素最多出現次數

單篇 ↗

計算nums裡面的元素出現最多的次數,如果次數一樣多就相加一起算最大

class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        ans = Counter(nums)
        ans = sorted(ans.items(),key=lambda x:x[-1],reverse=True)
        nums, counts = zip(*ans)
        ans = Counter(counts)
        for i in ans:
            return ans[i] * i
class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        # 統計每個元素的頻率
        freq = Counter(nums)
        
        # 找到最大頻率
        max_freq = max(freq.values())
        
        # 統計有多少個元素達到最大頻率,然後乘以最大頻率
        return sum(count for count in freq.values() if count == max_freq)
class Solution:
    def maxFrequencyElements(self, nums: List[int]) -> int:
        freq = Counter(nums)
        max_freq = max(freq.values())
        return max_freq * list(freq.values()).count(max_freq)
  • answer

    nums = [1,2,2,3,1,4],ans = 4

    nums = [1,2,3,4,5],ans = 5

    nums = [15],ans = 1

    nums = [10,12,11,9,6,19,11],ans = 2

計算年齡

單篇 ↗
from datetime import datetime

# 讀入生日與今天日期
birth_str = input("生日(yyyy-mm-dd):")
today_str = input("今天(yyyy-mm-dd):")

birth = datetime.strptime(birth_str, "%Y-%m-%d")
today = datetime.strptime(today_str, "%Y-%m-%d")

# 年齡計算(考慮是否過生日)
age = today.year - birth.year
if (today.month, today.day) < (birth.month, birth.day):
    age -= 1

# 分類
def classify_age(age):
    if 0 <= age <= 10:
        return 1
    elif age <= 17:
        return 2
    elif age <= 44:
        return 3
    elif age <= 64:
        return 4
    else:
        return 5

print(classify_age(age))

矩陣相乘

單篇 ↗
def counts():
    st1 = [int(i) for i in input().split(" ")]
    temp1 = []
    for i in range(st1[0]):
        st2 = list(map(int, input().split()))
        temp1.append(st2)

    st3 = [int(i) for i in input().split(" ")]
    temp2 = []
    for i in range(st3[0]):
        st4 = list(map(int, input().split()))
        temp2.append(st4)

    if st1[1] != st3[0]:
        return
    ans = [[0] * st3[1] for _ in range(st1[0])]

    for i in range(st1[0]):
        for j in range(st3[1]):
            for k in range(st1[1]):
                ans[i][j] += temp1[i][k] * temp2[k][j]
        
    return f"{ans}".replace(" ", "")
print(counts())

區間總和查詢

單篇 ↗
import sys
input = sys.stdin.readline

n, q = map(int,input().split())
n_list = list(map(int,input().split()))

prefix = [0] * (n+1)
prefix[1] = n_list[0]
for i in range(2,n+1):
    prefix[i] = prefix[i-1] + n_list[i-1]

for i in range(q):
    a,b = map(int,input().split())
    print(prefix[b] - prefix[a-1])
input:
5 3
3 2 3 1 2
1 3
2 4
1 5
out:
8
6
11

深度優先搜尋 (DFS)

單篇 ↗

概念

深度優先搜尋是一種樹的遍歷方式,會先遞迴地訪問子節點,再訪問兄弟節點。

程式碼實作

from collections import defaultdict

def dfs(Tree, now_node):
    print(now_node, end=" ")  # 先訪問當前節點
    for next_node in Tree[now_node]:  # 再遞迴訪問所有子節點
        dfs(Tree, next_node)

# 建立樹結構
tree = defaultdict(list)
root = ""

# 讀取輸入建立樹
while True:
    try:
        st, *sts = input().split()
        if root == "":
            root = st  # 第一個輸入的節點為根節點
        tree[st].extend(sts)  # 將子節點加入父節點的列表
    except:
        break

dfs(tree, root)

特點

  • 使用遞迴實作

  • 訪問順序:父節點 → 子節點 → 兄弟節點

  • 時間複雜度:O(V + E),V 為節點數,E 為邊數

尋找質因數(Finding Prime Factors)

單篇 ↗
def find_prime_factors(n):
    factors = set()
    i = 2
    while i * i <= n:
        while n % i == 0:
            factors.add(i)  # 加入集合,不重複
            n //= i
        i += 1
    if n > 1:
        factors.add(n)  # 剩下的數字也是質數
    return sorted(factors)

print(find_prime_factors(60))  # 🔹 輸出: [2, 3, 5]

循環質數

單篇 ↗
import sys
input = sys.stdin.readline

MAX = 10**6 + 1
Prime = [True] * (MAX+1)
Prime[0] = Prime[1] = False

for i in range(2,int(MAX**0.5)+1):
    if Prime[i]:
        for j in range(i * i,MAX+1, i):
            Prime[j] = False

# 循環找是否是循環質數
def check(n):
    temp_num = str(n)
    for j in str(n):
        if not Prime[int(temp_num)]:
            return False
        temp_num = temp_num[1::] + j
    return True

circle_list = []
for i in range(100,MAX):
    if Prime[i] and check(i):
        circle_list.append(i)
while True:
    a = input().strip()
    if a == '-1':
        break
    ans = 0
    i,j = map(int,a.split())
    for c in circle_list:
        if i <= c <= j:
            ans += 1
    if ans > 1:
        print(f"{ans} Circular Primes.")
    elif ans == 1:
        print("1 Circular Prime.")
    else:
        print("No Circular Primes.")

滑動視窗總和最大值

單篇 ↗
n, k = map(int, input().split())
x = list(map(int, input().split()))

temp = sum(x[0:k])
mx = temp
last = 0
for i in range(k, n):
    temp -= x[last]
    temp += x[i]
    last += 1
    mx = max(mx,temp)
print(mx)

圖片遺失:image.png

廣度優先搜尋 (BFS)

單篇 ↗

概念

廣度優先搜尋是一種層級式的遍歷方式,會先訪問完同一層的所有節點,再訪問下一層。

程式碼實作

from collections import defaultdict, deque

def bfs(Tree, start_node):
    queue = deque([start_node])  # 使用 queue 儲存待訪問節點
    
    while queue:
        now_node = queue.popleft()  # 取出隊列最前面的節點
        print(now_node, end=" ")
        
        for next_node in Tree[now_node]:  # 將所有子節點加入隊列
            queue.append(next_node)

# 建立樹結構(與 DFS 相同)
tree = defaultdict(list)
root = ""

while True:
    try:
        st, *sts = input().split()
        if root == "":
            root = st
        tree[st].extend(sts)
    except:
        break

bfs(tree, root)

特點

  • 使用佇列 (Queue) 實作

  • 訪問順序:按層級由上到下、由左到右

  • 時間複雜度:O(V + E)

  • 適合用於尋找最短路徑

質因數分解(Prime Factorization)

單篇 ↗
def prime_factorization(n):
    factors = []
    i = 2
    while i * i <= n:  # 只需要檢查到 sqrt(n)
        while n % i == 0:
            factors.append(i)
            n //= i  # 除去該因數
        i += 1
    if n > 1:  # 剩下的數字也是質數
        factors.append(n)
    return factors

print(prime_factorization(60))  # 🔹 輸出: [2, 2, 3, 5]
def prime_factorization(n):
    factors = []
    for i in range(2,int(n**0.5)+1):
        if n % i == 0:
            while n % i == 0:
                factors.append(i)
                n = n // i
    if n > 1:
        factors.append(n)
    return factors

質數建表

單篇 ↗
MAX = 10**6
prime = [True] * (MAX + 1)
prime[0] = prime[1] = False

# 建質數表(篩法)
for i in range(2, int(MAX ** 0.5) + 1):
    if prime[i]:
        for j in range(i * i, MAX + 1, i):
            prime[j] = False

num = int(input())

# 找上、下最近質數
up = num + 1
down = num - 1

while up <= MAX and not prime[up]:
    up += 1

while down >= 2 and not prime[down]:
    down -= 1

# 比較距離
if down < 2:
    print(up)
else:
    if abs(up - num) < abs(num - down):
        print(up)
    elif abs(up - num) > abs(num - down):
        print(down)
    else:
        print(min(up, down))

整數 -! 羅馬數字

單篇 ↗
def int_to_roman(num):
    val = [
        1000, 900, 500, 400,
        100, 90, 50, 40,
        10, 9, 5, 4,
        1
    ]
    sym = [
        "M", "CM", "D", "CD",
        "C", "XC", "L", "XL",
        "X", "IX", "V", "IV",
        "I"
    ]
    roman = ""
    for i in range(len(val)):
        while num >= val[i]:
            roman += sym[i]
            num -= val[i]
    return roman

# 範例:
print(int_to_roman(1994))  # 'MCMXCIV'

樹的遍歷與操作筆記

單篇 ↗

目錄

  1. 深度優先搜尋 (DFS)

  2. 廣度優先搜尋 (BFS)

  3. 樹的屬性計算


重要觀念整理

1. 資料結構選擇

演算法資料結構原因
DFS遞迴 / Stack需要回溯到上一層節點
BFSQueue需要按層級順序處理

2. 節點類型判斷

if parent[id] == -1:
    # 根節點:沒有父節點
    types = "root"
elif len(tree[id]) > 0:
    # 內部節點:有子節點
    types = "internal node"
else:
    # 葉節點:沒有子節點
    types = "leaf"

3. 深度與高度的計算

  • 深度 (Depth):從根節點往下傳遞,每往下一層 +1

    dfs(Tree, next_node, depth + 1)
  • 高度 (Height):從葉節點往上回傳,取子節點中的最大值

    height = max(dfs(Tree, next_node, depth + 1), height)

4. defaultdict 的使用

from collections import defaultdict
tree = defaultdict(list)

好處:

  • 自動初始化不存在的 key 為空 list

  • 不需要檢查 key 是否存在就可以直接 append


時間複雜度分析

操作時間複雜度說明
DFS 遍歷O(V + E)每個節點和邊都訪問一次
BFS 遍歷O(V + E)每個節點和邊都訪問一次
計算深度/高度O(V + E)使用 DFS 遍歷一次

其中 V 是節點數,E 是邊數。對於樹來說,E = V - 1。


常見應用

DFS 適用場景

  • 路徑搜尋

  • 拓撲排序

  • 偵測循環

  • 計算連通分量

BFS 適用場景

  • 最短路徑(無權重圖)

  • 層級遍歷

  • 找到距離某節點最近的節點

樹的屬性計算

單篇 ↗

概念

計算樹中每個節點的重要屬性:

  • Parent(父節點):該節點的上一層節點

  • Depth(深度):從根節點到該節點的距離

  • Height(高度):從該節點到最遠葉節點的距離

  • Type(類型):root(根)、internal node(內部節點)、leaf(葉節點)

程式碼實作

from collections import defaultdict

def dfs(Tree, now_node, depth):
    depths[now_node] = depth  # 記錄當前節點深度
    height = 0
    
    # 遞迴計算所有子節點的高度
    for next_node in Tree[now_node]:
        height = max(dfs(Tree, next_node, depth + 1), height)
    
    heights[now_node] = height  # 記錄當前節點高度
    return height + 1  # 回傳給父節點

# 初始化
tree = defaultdict(list)
n = int(input())
parent = [-1] * n  # parent[i] = i 的父節點
depths = [0] * n   # depths[i] = i 的深度
heights = [0] * n  # heights[i] = i 的高度

# 讀取輸入
for _ in range(n):
    id, k, *c = map(int, input().split())
    for i in c:
        parent[i] = id  # 設定子節點的父節點
    tree[id].extend(sorted(c))  # 將子節點排序後加入

# 找到根節點並開始 DFS
root = parent.index(-1)
dfs(tree, root, 0)

# 輸出結果
for id in range(n):
    types = ""
    if parent[id] == -1:
        types = "root"
    elif len(tree[id]) > 0:
        types = "internal node"
    else:
        types = "leaf"
    
    print(f"node {id}: parent = {parent[id]}, depth = {depths[id]}, "
          f"height = {heights[id]}, {types}, {tree[id]}")
import sys
sys.setrecursionlimit(1000000)  # 增加遞迴深度限制

當樹的深度很大時,Python 預設的遞迴深度可能不夠,需要手動增加限制。

羅馬數字 -! 整數

單篇 ↗
def roman_to_int(s):
    roman = {
        'I': 1, 'V': 5, 'X': 10,
        'L': 50, 'C': 100,
        'D': 500, 'M': 1000
    }
    total = 0
    prev = 0
    for ch in reversed(s):
        val = roman[ch]
        if val < prev:
            total -= val
        else:
            total += val
            prev = val
    return total

# 範例:
print(roman_to_int("MCMXCIV"))  # 1994

dp動態規劃

單篇 ↗

你的任務是找出:在所有可能的連續天數當中,哪一段的總收益最高?這個最高收益就是 你的程式必須輸出的連續最大收益。假設某人連續6天的投資結果為: −99, 10, −9, 10, −5, 4 在這些天數中,連續某一段期間的最大總收益是: 10 + (−9) + 10 = 11 這段最佳投資期間出現在第2、3、4天。請你寫出能計算這個「連續最大收益」的程式。

num = int(input())
for i in range(num):
    rounds = int(input())
    if rounds == 0:
        break
    else:
        moneys = list(map(int,input().split(' ')))
        dp = moneys
        for i in range(1,len(moneys)):
            dp[i] = max(moneys[i], moneys[i] + dp[i-1])

        # 暴力解
        # ans = max(ans,max(moneys))
        # for i in range(len(moneys)):
        #     temp_n = 0
        #     for j in range(i,len(moneys)):
        #         temp_n += moneys[j]
        #         ans = max(ans,temp_n)
    if max(dp) > 0:
        print(f"The maximum winning streak is {max(dp)}.")
    else:
        print("Losing streak.")

Linked List

單篇 ↗
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def mergeTwoLists(self, head: ListNode | None) -> ListNode | None:

        current = head

        while current and current.next:
            if current.val == current.next.val:
                current.next = current.next.next
            else:
                current = current.next
        return head


# ========== 測試 ==========

def create_linked_list(values):
    if not values:
        return None
    head = ListNode(values[0])
    current = head
    for val in values[1:]:
        current.next = ListNode(val)
        current = current.next
    return head

def linked_list_to_array(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result

def test_case(input_values):
    head = create_linked_list(input_values)
    
    solution = Solution()
    result = solution.mergeTwoLists(head)
    
    print(linked_list_to_array(result))
    

# 執行測試
test_case([1, 1, 2])
test_case([1, 1, 2, 3, 3])
test_case([1, 1, 1])
test_case([1, 2, 3])
test_case([1])
test_case([])
test_case([1, 1, 1, 2, 2, 3])

list comprehension(filter篩選)

單篇 ↗
scores = (50,60,60,40,80)

# s 表示內容, for s in scores 表示s 是 scores裡面的內容, if s >=60 表示條件
p = [s for s in scores if s >=60]

print(p)
print(len(p))

example:

chinese = int(input())
english = int(input())
math = int(input())

total = chinese + english + math
avg = total / 3

cnt = 0

if len([s for s in (chinese,english,math) if s >= 90]) >= 2:
  rank = "A"
else:
  rank = "B"

print(f'總分:{total}, 平均:{avg:.0f}, 等級:{rank}')

list comprehension(mapping映照)

單篇 ↗
scores = (50,60,60,40,80)

# 1 if s >=60 else 0 表示如果為真=1,否=0, for s in scores 表示 s 是 scores裡面的內容
p = [1 if s >= 60 else 0 for s in scores]
#    真____條件____否

print(p)
print(sum(p))

example:

chinese = int(input())
english = int(input())
math = int(input())

total = chinese + english + math
avg = total / 3

cnt = 0

if sum([1 if s >= 90 else 0 for s in (chinese,english,math)]) >= 2:
  rank = "A"
else:
  rank = "B"

print(f'總分:{total}, 平均:{avg:.0f}, 等級:{rank}')

Python Day 1

單篇 ↗

字典推導式(Dictionary Comprehension)是什麼?

基本語法:

'''
{key: value for 變數 in 可迭代對象}

==

result = {}
for 變數 in 可迭代對象:
    result[key] = value

''' 

進階:

'''
{key: value for 變數 in 可迭代對象}

可迭代對象 可以加上其他功能
ex:判斷式、反轉字典、合併列表

反轉字典:
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
print(inverted)

合併列表:
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
person = {k: v for k, v in zip(keys, values)}
print(person)
'''

使用find()和rfind()來尋找第一個值的位置和最後一個值得位置

在使用sorted()要注意要把原本的給覆蓋掉,要不然print出來不會有排序

Format()用法

可以利用format來補0、進位轉化、小數格式化

'''
a = 50
b = 100
a,b = format(a,"020b"),format(b,"020b")
'''

Zip()用法

用於將多個可迭代對象(如列表、元組)打包成對應元素的組合

ex:配對兩個列表、處理多個列表、用於字典、用於遍歷多個列表、用於 * 解壓縮、計算 Hamming 距離

'''
用於遍歷多個列表:
students = ["Alice", "Bob", "Charlie"]
scores = [90, 85, 88]

for name, score in zip(students, scores):
    print(f"{name} 得分: {score}")

用於 * 解壓縮:
zipped_list = [('Alice', 90), ('Bob', 85), ('Charlie', 88)]
names, scores = zip(*zipped_list)

print(names)  # ('Alice', 'Bob', 'Charlie')
print(scores) # (90, 85, 88)

計算 Hamming 距離:
a = "1100101011"
b = "1001101010"

hamming_distance = sum(x != y for x, y in zip(a, b))
print(hamming_distance)

'''

Python Day 2

單篇 ↗

題目:

st 的內容包括數字、加減乘除、小括號。如同一般小括號的用法, 在一組小括號中可以包括另一組小括號, 請找出 st 中的小括號最多 有幾層? 例如: ((1) + ((2) + 3) + 4)

1 有 2 層, 如((1) + ((2) + 3) + 4)

2 有 3 層, 如((1) + ((2) + 3) + 4)

3 有 2 層, 如((1) + ((2) + 3) + 4)

4 有 1 層, 如((1) + ((2) + 3) + 4)

def counts():
    response = [i for i in input()]
    temp = 0
    ans = 0
    for i in response:
        if i == "(":
            temp += 1
            ans = max(ans,temp)
        elif i == ")":
            temp -= 1
    return ans

print(counts())

利用左右括號去判斷他有多少層,當遇到左括號就+1,而遇到右括號就-1

Python Day 3

單篇 ↗
def numbers():
    number = input()
    ans = [0,0]
    temp2 = []
    for i in range(len(number)):
        ans[0] += int(number[i])
    for i in range(2,int(number)):
        if int(number)%i == 0:
            temp2.append(i)
    if len(temp2) == 0:
        return 0
    else:
        number1 = []
        for i in temp2:
            while int(number)%i == 0:
                if int(number)%i == 0:
                    number1.append(i)
                    number = int(number)//i
    for i in range(len(number1)):
        temp3 = [int(i) for i in str(number1[i])]
        for j in range(len(temp3)):
            ans[1] += temp3[j]
    if ans[0] == ans[1]:
        return 1
    return 0
print(numbers())

簡化後:

def numbers():
    number = input()
    temp2 = []
    first_sum = [int(i) for i in number]
    number = int(number)
    for i in range(2,number):
        while number % i == 0:
            temp2.append(i)
            number //= i
    if not temp2:
        return 0
 
    factors = 0
    for i in range(len(temp2)):
        temp3 = [int(i) for i in str(temp2[i])]
        factors += sum(temp3)

    if first_sum[0] == factors:
        return 1
    return 0
print(numbers())

python未完成放置區

單篇 ↗