---
# System prepended metadata

title: APCS實作題目
tags: [APCS檢定營隊]

---

## A
```python=
A = input()
print('Step1: {}'.format(int(A[1])+int(A[3])))
print('Step2: {}'.format(int(A[2])+int(A[0])))
if int(A[1])+int(A[3]) > int(A[2])+int(A[0]):
    print("Step1 > Step2")
else:
    print("Step1 <= Step2")
```
## B
```python=
#要求使用者輸入存款的本金
principal = float(input(""))

# 要求使用者輸入年利率
interest_rate = float(input(""))

# 要求使用者輸入存款期限
deposit_period = float(input(""))

# 計算複利利息
final_amount = principal * ((1 + interest_rate/100) ** deposit_period)

# 輸出最終的本利和
print(final_amount)
```
## C
```python=
# 輸入卡片類型
card_type = input()
# 輸入卡片有效期
expiration_date = input()
# 獲取當前日期
current_date = '20230619'
# 判斷是否允許進入
if card_type == "A" and expiration_date <= current_date:
    print("Allow")
elif card_type == "B" and expiration_date >= current_date:
    print("Allow")
else:
    print("Not Allow")
```
## D
```python=
# 要求使用者輸入學生的分數
score = int(input(""))

# 根據評估標準判斷成績等級
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "E"

# 輸出成績等級
print( grade)

```
## E
```python=
# 要求使用者輸入初始狀態
current_state = "A"

while True:
    # 要求使用者輸入動作
    action = input("")
    if action == "0":
        break
    if current_state == "A":
        if action == "1":
            current_state = "B"
            print("update to B")
        elif action == "2":
            current_state = "C"
            print("update to C")
    elif current_state == "B":
        if action == "1":
            current_state = "C"
            print("update to C")
        elif action == "2":
            current_state = "A"
            print("update to A")
    elif current_state == "C":
        if action == "1":
            current_state = "A"
            print("update to A")
        elif action == "2":
            current_state = "B"
            print("update to B")
    
        
print(f"final is {current_state}")
```
## G
```python=
# 要求使用者輸入正整數
num = int(input())

# 初始化總和變數
total = 0

# 使用while迴圈計算每個位數的總和
while num > 0:
    digit = num % 10  # 獲取最右邊的位數
    total += digit   # 加到總和中
    num //= 10       # 刪除最右邊的位數

# 輸出總和的值
print( total)
```
## H
```python=
# 初始化奇數總和
odd_sum = 0
# 迴圈計算奇數總和
for num in range(1, 51, 2): # 從1到50的奇數，步長為2
    if num % 7 == 0:  # 能被7整除的數字跳過
        continue
    odd_sum += num #輸出結果
print( odd_sum)

```
## I
```python=
# 輸入上限值 n
n = int(input())
# 初始化奇數總和和偶數總和
odd_sum = 0
even_sum = 0
# 迴圈計算奇數和偶數總和
for num in range(1, n + 1):
    if num > 100:
        break
    if num % 7 == 0:
        continue
    if num % 2 == 0:  # 偶數
        even_sum += num
    else:  # 奇數
        odd_sum += num
# 輸出結果
print(odd_sum)
print(even_sum)

```
## K
```python=
sentence = input().lower()
keyword = input().lower()

count = 0
start_index = 0

while True:
    index = sentence.find(keyword, start_index)
    if index == -1:
        break
    count += 1
    start_index = index + 1

print(count)
```
## L
```python=
# 定義函式執行運算
def calculate(num1, num2, operator):
    if not num1.isdigit() or not num2.isdigit():
        result = "Undefined"
    else:
        num1 = float(num1)
        num2 = float(num2)
        if operator == "+":
            result = num1 + num2
        elif operator == "-":
            result = num1 - num2
        elif operator == "*":
            result = num1 * num2
        elif operator == "/":
            result = num1 / num2
        else:
            result = "Undefined"
    return result

# 要求使用者輸入數字和運算符
num1 = input("")
num2 = input("")
operator = input("")

# 呼叫函式執行運算
result = calculate(num1, num2, operator)
print(result)
```
## M
```python=
def cmp(item):
    return int(item[1])
n = int(input())
lst = []
for i in range(n):
    lst.append(input().split())
lst.sort(key=cmp,reverse=True)
print(lst)
```
## N
```python=
car = []
while True:
    user = input().split()
    if len(user)==1 and user[0]=="-1":
        break 
    for i in range(int(user[0])):
        if len(car)==0:
            break
        car.pop(0)
    for i in range(1,len(user)):
        if len(car)==3:
            break
        car.append(user[i])
    print(f"now is {car}")
print(f"final is {car}")
```
## O
```python=
def hanoi(n, source, target, auxiliary):
    if n > 0:
        # 將 n-1 個圓盤從起始柱移動到輔助柱
        hanoi(n - 1, source, auxiliary, target)
        # 移動第 n 個圓盤到目標柱
        print(f"disk {n} from pillar {source} to pillar {target}")
        # 將 n-1 個圓盤從輔助柱移動到目標柱
        hanoi(n - 1, auxiliary, target, source)


# 計算河內塔遊戲次數
n = int(input())
hanoi(n, "pillar 1", "pillar 3", "pillar 2")
# 計算次數公式：次數 = 2^n - 1
total_moves = 2 ** n - 1
print(total_moves)


```
## P
```python=
stack = []
n = int(input())

for i in range(n):
    ans = 0
    user_input = input()
    for k in range(len(user_input)):
        if user_input[k]==".":
            continue
        stack.append(user_input[k])
        while len(stack)>=2 and stack[-1]=="q" and stack[-2]=="p":
                ans+=1
                stack.pop(-1)
                stack.pop(-1)

    print(ans)
    stack.clear()
```
## Q
```python=
def preorder(tree, index=1):
    if len(tree) < index:
        return
    print(tree[index - 1], end='')
    preorder(tree, index * 2)
    preorder(tree, index * 2 + 1)


def postorder(tree, index=1):
    if len(tree) < index:
        return
    postorder(tree, index * 2)
    postorder(tree, index * 2 + 1)
    print(tree[index - 1], end='')


def inorder(tree, index=1):
    if len(tree) < index:
        return
    inorder(tree, index * 2)
    print(tree[index - 1], end='')
    inorder(tree, index * 2 + 1)
tree = [4, 2, 6, 1, 3, 5, 7]
print("Preorder Traversal:")
preorder(tree)
print()
print("Postorder Traversal:")
postorder(tree)
print()
print("Inorder Traversal:")
inorder(tree)

```
## R
```python=
n = int(input())
data = list(map(int,input().split()))
B = [0 for i in range(n)]
B[0] = data[0]
for i in range(n):
    B[i]=B[i-1]+data[i]
print(' '.join(list(map(str,B))))
```
## S
```python=
nums = list(map(int,input().split()))
target = int(input())
n = len(nums)
for i in range(n - 1):
    for j in range(i + 1, n):
        if nums[i] + nums[j] == target:
           print(i,j)

```
## T
```python=
queue = [""]
chars = ['A', 'B', 'C']
while True:
    next_queue = []
    update = False
    for i in range(3):
        for k in range(len(queue)):
            if chars[i] not in queue[k]:
                next_queue.append(queue[k]+chars[i])
                update = True
    if not update:
        break
    queue = next_queue
queue.sort()
print(queue)
```
## U
```python=
chars = ['A', 'B', 'C ','D','E']

def find_combinations(chars):
    combinations = []
    n = len(chars)
    for i in range(n):
        for j in range(i+1, n):
            for k in range(j+1, n):
                combination = chars[i].strip() + chars[j].strip() + chars[k].strip()
                combinations.append(combination)
    return combinations
result = find_combinations(chars)
print(result)


```
## W
```cpp=
#include <bits/stdc++.h>

#define x first
#define y second
using namespace std;

int main() {
    int n, answer = 0;
    cin >> n;
    pair<int, int> data[n];
    for (int i = 0; i < n; i++)
        cin >> data[i].x >> data[i].y;
    sort(data, data + n);
    pair<int, int> now = data[0];
    for (int i = 1; i < n; i++) {
        //cout<<data[i].x<<" "<<data[i].y<<endl;
        if (data[i].x <= now.y && data[i].x >= now.x)
        {
            now.y = max(data[i].y, now.y);
            if(i==n-1)
                answer += (now.y - now.x);
        }
        else {
            answer += (now.y - now.x), now = data[i];
            if(i==n-1)
                answer += (now.y - now.x);
        }
        //cout<<now.x<<" "<<now.y<<endl<<endl;
    }
    if(n==1)
    answer += (now.y - now.x);
    cout<<answer;

}
```
## X
```python=
#include <bits/stdc++.h>

using namespace std;
int data[514][514];
int dir[4][2]={{0,-1},{0,1},{-1,0},{1,0}};
int n,w,s,e,area;
void update(int x,int y)
{
    n = min(n,y-1);
    e = max(e,x-1);
    s = max(s,y-1);
    w = min(w,x-1);
}
void count(int x,int y)
{
    if(data[x][y]==1)
    {
        update(x,y);
        data[x][y]=0;
        area++;
        for(int i=0;i<4;i++)
            count(x+dir[i][0],y+dir[i][1]);
    }


}
int main() {
    int x, y;
    cin >> x >> y;
    memset(data,0,sizeof(data));
    for (int i = 1; i <= y; i++) {
        for (int j = 1; j <= x; j++) {
            cin>>data[j][i];
        }
    }
    for (int i = 0; i < y; i++) {
        for (int j = 0; j < x; j++) {
            if(data[j][i]==1)
            {
                n=w=9999;
                e=s=-1;
                area=0;
                count(j,i);
                cout<<w<<" "<<n<<" "<<e<<" "<<s<<" "<<area<<endl;
            }
        }
    }


}
```
## Y
```python=
from re import T
n=int(input())
f=[int(x) for x in input().split()]
visit=[False]*n
n_group=0
for i in range(n):
  if visit[i]:
    continue
  n_group+=1
  visit[i]=True
  p=f[i]
  while p!=i:
    visit[p]=True
    p=f[p]
print(n_group)
```
## Z
```python=
#include <bits/stdc++.h>

#define max_size 101
using namespace std;
map<char, int> f;

void build() {
    f['A'] = 10;
    f['B'] = 11;
    f['C'] = 12;
    f['D'] = 13;
    f['E'] = 14;
    f['F'] = 15;
    f['G'] = 16;
    f['H'] = 17;
    f['I'] = 34;
    f['J'] = 18;
    f['K'] = 19;
    f['L'] = 20;
    f['M'] = 21;
    f['N'] = 22;
    f['O'] = 35;
    f['P'] = 23;
    f['Q'] = 24;
    f['R'] = 25;
    f['S'] = 26;
    f['T'] = 27;
    f['U'] = 28;
    f['V'] = 29;
    f['W'] = 32;
    f['X'] = 30;
    f['Y'] = 31;
    f['Z'] = 33;
}

void check(string data) {
    int answer = 0;
    for (int i = 0; i < data.length(); i++) {
        if (i == 0) {
            answer += (f[data[i]] / 10) * 1 + (f[data[i]] % 10) * 9;
        } else {
            answer += ((data[i] - '0') * (9 - i));
            if(i==9)
                answer += (data[i] - '0');
            //cout<< (data[i] - '0')<<" "<<9-i<<endl;
        }
        //cout<<answer<<endl;
    }

    if(answer%10==0)
    cout<<data<<" ";
}

int main() {
    build();
    check("A193456789");
    int t;
    cin >> t;
    while (t--) {
        string index;
        string data;
        cin >> index >> data;
        for(int i=0;i<3-index.length();i++)
            cout<<0;
        cout<<index<<" ";
        for (int i = 0; i < data.length(); i++) {
            if (data[i] == '*') {
                if(i==0)
                {
                    for(char t = 'A';t<='Z';t++)
                        data[i]=t,check(data);
                }else
                {
                    for(char t='0';t<='9';t++)
                        data[i]=t,check(data);
                }
            }

        }
        cout<<endl;

    }


}
```
