---
# System prepended metadata

title: 我的ZJ解題程式碼紀錄
tags: [Python]

---

# 我的ZJ解題程式碼紀錄
# Python 的部分
>[!Tip]持續解題(更新)中

:::danger
有紅底的是老師要的作業
:::
## a

### a024
```python=
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
num1, num2 = map(int, input().split())
print(gcd(num1, num2))
```

### a058
```python=
n = int(input())
mod0 = mod1 = mod2 = 0
for i in range(n):
    m = int(input())
    if m%3 == 0:
        mod0 += 1
    elif m%3 ==1:
        mod1 += 1
    elif m%3 ==2:
        mod2 += 1
print(mod0, mod1, mod2)
```

### a095
```python=
while True:
    try:
        a,b=map(int,input().split())
        if a==b:
            print(b)
        else:
            print(b+1)
    except:
        break
```

### a104
:::danger
```python=
while True:
    try:
        n = int(input())
        p = list(map(int, input().split()))
        print(p.sort())
    except:
        pass
```
:::

### a148
```python=
while True:
    try:
        input_data = input().split()
        n = int(input_data[0])
        scores = list(map(int, input_data[1:n+1]))
        average = sum(scores) / n
        if average > 59:
            print("no")
        else:
            print("yes")
    except EOFError:
        break
```

### a271
:::spoiler 太長了，請點開看
```python=
import sys
def solve():
    x, y, z, w, n, m = map(int, sys.stdin.readline().split())
    try:
        input_str = sys.stdin.readline().strip()
        if not input_str:
            sys.stdout.write(f"{m}g\n")
            return
        carrots = map(int, input_str.split())
    except EOFError:
        sys.stdout.write(f"{m}g\n")
        return
    poison = 0
    for carrot in carrots:
        if poison > 0:
            m -= poison * n
            if m <= 0:
                sys.stdout.write("bye~Rabbit\n")
                return
        if carrot == 1:
            m += x
        elif carrot == 2:
            m += y
        elif carrot == 3:
            m -= z
        elif carrot == 4:
            m -= w
            poison += 1
        if m <= 0:
            sys.stdout.write("bye~Rabbit\n")
            return
    sys.stdout.write(f"{m}g\n")
def main():
    t = int(sys.stdin.readline())
    for _ in range(t):
        solve()
if __name__ == "__main__":
    main()
```
:::

### a539
:::danger
```python=
while True:
	try:
		n = int(input())
		nums = list(map(int, input().split()))
		result = 0
		for i in range(n):
			for j in range(n-i-1):
				if nums[j] > nums[j+1]:
					nums[j], nums[j+1] = nums[j+1], nums[j]
					result += 1
		print("Minimum exchange operations :",result)
	except:
		break
```
:::

### a737
:::danger
```python=
t = int(input())
for i in range(t):
    s = [*map(int, input().split())]
    r = s.pop(0)
    s.sort()
    vito_home = s[r // 2]
    ans = 0
    for house in s:
        ans += abs(house - vito_home)
    print(ans)
```
:::

### a982
:::danger
:::spoiler 太長了，請點開看
```python=
n = int(input())
length = [[-1] * n for _ in range(n)]
q = []
maze = [list(input()) for _ in range(n)]

q.append((1, 1))
length[1][1] = 1
maze[1][1] = '#'
while q:
    now_p = q.pop(0)
    r, c = now_p[0], now_p[1]
    if maze[r][c + 1] == '.':
        q.append((r, c + 1))
        length[r][c + 1] = length[r][c] + 1
        maze[r][c + 1] = '#'
    if maze[r + 1][c] == '.':
        q.append((r + 1, c))
        length[r + 1][c] = length[r][c] + 1
        maze[r + 1][c] = '#'
    if maze[r][c - 1] == '.':
        q.append((r, c - 1))
        length[r][c - 1] = length[r][c] + 1
        maze[r][c - 1] = '#'
    if maze[r - 1][c] == '.':
        q.append((r - 1, c))
        length[r - 1][c] = length[r][c] + 1
        maze[r - 1][c] = '#'
if length[n-2][n-2] == -1:
    print('No solution!')
else:
    print(length[n-2][n-2])
```
:::

## b

### b581
```python=
n = int(input())
for i in range(n):
    h = list(map(int, input().split()))
    print(sum(h))
```

### b838
:::danger
:::spoiler 太長了，請點開看
```python=
T = int(input())
for i in range(T):
    a = 0
    s = input()
    stk = []
    flag = True
    for c in s:
        if c == "(":
            stk.append(c)
        elif c == " ":
            continue
        elif len(stk) > 0 and (c == ')' and stk[-1] == '('):
            stk.pop()
            a+=1
        else:
            flag = False
            break
    if len(stk) > 0:
        flag = False
    if flag:
        print(a)
    else:
        print("0")
```
:::

### b882
```python=
H, M, S = map(int, input().split())
M += S // 60
S %= 60
H += M // 60
M %= 60
H %= 24
print(f"{H:02}:{M:02}:{S:02}")
```

### b969
```python=
name = list(map(str, input().split()))
first = input()
for i in range(len(name)):
    print(first+", " + name[i])
```

## c

### c010
```python=
nums, L = [], 0
while True:
    try:
        nums.append(int(input()))
        nums.sort()
        L += 1
        if L % 2:
            print(nums[L // 2])
        else:
            print( (nums[L // 2] + nums[L // 2 - 1]) // 2 )
    except EOFError:
        break
```

### c067
```python=
seting=0
while True:
  seting +=1
  n = int(input())
  if n == 0:
    break
  a = list(map(int, input().split()))
  p = sum(a)//len(a)
  m=0
  for i in a:
    if i<p:
      m +=(p-i)
  print(f"Set #{seting}")
  print(f"The minimum number of moves is {m}.")
```

### c123
:::spoiler 太長了，請點開看
```python=
while True:
    n=int(input())
    if n==0:
        break
    while True:
        num=list(map(int,input().split()))
        if num==[0]:
            break
        stack=[0]
        y=[i for i in range(1,n+1)]
        f=True
        for i in num:
            while True:
                if i==stack[-1]:
                    stack.pop()
                    break
                elif i>stack[-1]:
                    stack.append(y.pop(0))
                elif i<stack[-1]:
                    f=False
                    break
            if f==False:
                print("No")
                break
        else:
            print("Yes")
```
:::

### c186
```python=
n = list(map(str, input().split()))
for i in range(len(n)):
    print(n[i])
```

### c290
```python=
print(abs(sum(int(c)*(-1)**i for i,c in enumerate(input()))))
```

### c379
```python=
n = int(input())
print((n * 3) // 10)
```

### c382
```python=
a, b, c = input().split()
a = int(a)
c = int(c)
if b == "+":
    print(a+c)
elif b == "-":
    print(a-c)
elif b == "*":
    print(a*c)
elif b == "/":
    print(a//c)
```

### c680
```python=
a = int(input())
ascore = 100 // a
cans = list(input())
n = int(input())
for i in range(n):
    score = 0
    nans = list(input())
    for j in range(a):
        if cans[j] == nans[j]:
            score = score + ascore
    print(score)
```

### c760
```python=
[print(x.capitalize()) for x in (input().split())]
```

### c929
```python=
h = input()
n = list(map(str, input().split(h)))
for i in range(len(n)):
    print(n[i])
```

## d

### d041
```python=
n = int(input())
for i in range(n):
    input()
    now_date = list(map(int, input().split('/')))
    born_date = list(map(int, input().split('/')))
    age = now_date[2] - born_date[2]
    if (now_date[1], now_date[0]) < (born_date[1], born_date[0]):
        age -= 1
    if age < 0:
        print(f"Case #{i+1}: Invalid birth date")
    elif age > 130:
        print(f"Case #{i+1}: Check birth date")
    else:
        print(f"Case #{i+1}: {age}")
```

### d046
```python=
n = int(input())
w = list(map(int, input().split()))
total = 0
for i in w:
    if i <= 10:
        total += 1
print(total)
```

### d049
```python=
n = int(input())
print(n-1911)
```

### d051
```python=
a = float(input())
b = ((a-32)*5/9)
print("%.3f"%(b))
```

### d060
```python=
a=int(input())
if a<25:
    print(25-a)
elif a==25:
    print(0)
elif a>25:
    print((60-a)+25)
```

### d064
```python=
p = int(input())
if p%2 == 1:
    print('Odd')
else:
    print('Even')
```
### d065
```python=
a, b, c = map(int, input().split())
print(max(a, b, c))
```
### d066
```python=
h, m = map(int, input().split())
if h < 7 or h == 7 and m < 30 or h >= 17:
    print("Off School")
else:
    print("At School")
```

### d068
```python=
g = int(input())
if g>50:
    g = g-1
print(g)
```

### d074
```python=
people = int(input())
n = list(map(int, input().split()))
n.sort()
print(n[-1])
```

### d124
```python=
while True:
    try:
        n = int(input())
        if n%3 == 0:
            print("yes")
        else:
            print("no")
    except EOFError:
        break
```

### d143
```python=
times = int(input())
for _ in range(times):
    a,b=map(int,input().split())
    if (a>b):print(">")
    elif (a<b):print("<")
    else:print("=")
```

### d150
```python=
t = int(input())
for _ in range(t):
    n = int(input())
    prices = list(map(int, input().split()))
    prices.sort(reverse=True)
    max_saving = 0
    for i in range(2, n, 3):
        max_saving += prices[i]
    print(max_saving)
```

### d318
:::danger
```python=
while True:
  try:
    n = int(input())
    if n < 0:
      break
    elif n == 0:
      print("0")
      continue
    s = ""
    while n > 0:
      s += str(n%3)
      n //= 3
    print(s[::-1])
  except EOFError:
    break
```
:::

### d452
:::danger
```python=
n = int(input())
for _ in range(n):
    lst = [*map(int, input().split())]
    m = lst.pop(0)
    for i in range(m - 1):
        min_idx = i
        for j in range(i + 1, m):
            if lst[j] < lst[min_idx]:
                min_idx = j
        lst[i], lst[min_idx] = lst[min_idx], lst[i]
    total = 0
    for j in range(m):
        total += abs(lst[m // 2] - lst[j])
    print(total)
```
:::

### d460
```python=
age = int(input())
if age < 6 :
    print('0')
elif age >5 and age < 12 :
    print(590)
elif age > 11 and age < 18 :
    print(790)
elif age > 17 and age < 60 :
    print(890)
else:
    print(399)
```

### d490
```python=
a, b = map(int, input().split())
zum = 0
for i in range(b-a+1):
    if (a+i) % 2 == 0:
        zum += (a+i)
print(zum)
```

### d498
```python=
n = int(input())
for i in range(n):
    print("I don\'t say swear words!")
```

### d507
```python=
x=[int(n) for n in input().split()]
x.sort()
h=x[0]*x[0]+x[1]*x[1]
r=x[2]*x[2]
if h==r:
    print('right triangle')
if h>r:
    print('acute triangle')
if h <r:
    print('obtuse triangle')
```

### d562
```python=
while True:
  try:
    n=int(input())
    woo=[int(i) for i in input().split()]
    for i in range(n):
      print(*woo)
      woo.pop(0)
      woo.reverse()
  except EOFError:
    break
```

## e

### e155
:::danger
```python=
while True:
    try:
        n = int(input())
        if n == 0:
            break
        q = []
        discard = []
        for i in range(1, n + 1):
            q.append(i)
        while len(q) > 1:
            discard.append(q.pop(0))
            q.append(q.pop(0))
        print('Discarded cards: ' + ', '.join(map(str, discard)))
        print('Remaining card: ' + str(q[0]))
    except:
        break
```
:::

### e286
```python=
k = list(map(int, input().split()))
h = list(map(int, input().split()))
m = list(map(int, input().split()))
n = list(map(int, input().split()))
kl = sum(k)
hl = sum(h)
ml = sum(m)
nl = sum(n)
print(str(kl)+":"+str(hl))
print(str(ml)+":"+str(nl))
if kl < hl and ml < nl:
    print("Lose")
elif kl > hl and ml > nl:
    print("Win")
else:
    print("Tie")
```

### e447
:::danger
```python=
queue = []
n = int(input())
for _ in range(n):
    operation = list(map(int, input().split()))
    if operation[0] == 1:
        queue.append(operation[1])
    elif operation[0] == 2:
        if queue:
            print(queue[0])
        else:
            print(-1)
    elif operation[0] == 3:
        if queue:
            queue.pop(0)
```
:::

### e484
```python=
a=int(input())
n=0
for i in range(2,a//2+1):
    if a%i==0:
        print('no')
        n=1
        break
if n==0:
    print('yes')
```

### e561
:::danger
```python=
n = int(input())
for k in range(n):
	l = int(input())
	nums = list(map(int, input().split()))
	result = 0
	for i in range(l):
		for j in range(l-i-1):
			if nums[j] > nums[j+1]:
				nums[j], nums[j+1] = nums[j+1], nums[j]
				result += 1
	print(f"Optimal train swapping takes {result} swaps.")
```
:::

### e598
```python=
a=int(input())
b=[100000110,199999998,200000001,999999979,999999937]
if a in b:
    print("yes")
else:
    print("no")
```

### e924
:::danger
:::spoiler 太長了，請點開看
```python=
T = int(input())
for i in range(T):
    s = input()
    stk = []
    flag = True
    for c in s:
        if c == '(' or c == '[' or c == '{' or c == '<':
            stk.append(c)
        elif len(stk) > 0 and ((c == ')' and stk[-1] == '(') or (c == ']' and stk[-1] == '[') or (c == '}' and stk[-1] == '{') or (c == '>' and stk[-1] == '<')):
            stk.pop()
        else:
            flag = False
            break
    if len(stk) > 0:
        flag = False
    if flag:
        print('Y')
    else:
        print('N')
```
:::

### e997
```python=
h = list(map(str, input().split()))
n = int(input())
h.reverse()
print(h[n-1])
```

## f

### f017
```python=
print('-'.join(input().strip()))
```

### f073
```python=
n=int(input())
y=[str(x) for x in input().split()]
z=int(input())
print(*y[z:],*y[:z])
```

### f165
```python=
try :
    while True:
        a,b = map(int,input().split())
        if b==0 or a%b == 0:
            print("OK!")
        else:
            print(a%b)
except EOFError:
    pass
```

### f345
```python=
n = int(input())
rew = list(map(int, input().split()))
rew.reverse()
print(*rew)
```

### f351
```python=
print(*input().split())
```

### f442
```python=
chick_count = int(input())
chicks = [int(i) for i in input().split()]
e = int(input())
round = int(input())
catched = [int(i) for i in input().split()]

for i in range(round):
  p = chicks.index(catched[i])
  tmp = e
  e = chicks[p]
  chicks[p] = tmp
print(*chicks)
```

### f698
:::danger
```python=
stk=[]
eval_line=input().split()
for c in eval_line:
    if c=='+':
        stk.append(int(stk.pop())+int(stk.pop()))
    elif c=='-':
        stk.append(0-int(stk.pop())+int(stk.pop()))
    elif c=='*':
        stk.append(int(stk.pop())*int(stk.pop()))
    elif c=='/':
        b=int(stk.pop())
        a=int(stk.pop())
        stk.append(a//b)
    else:  
        stk.append(int(c))
print(*stk)
```
:::

### f925
```python=
n, m = map(int, input().split())
if n == 6 and m == 12:
    print("Yes")
else:
    print("No")
```

### f987
:::spoiler 太長了，請點開看
```python=
import time
k=(time.localtime().tm_sec)
if k==1:
    print("Hello, World!")
    time.sleep(1)
elif k==2:
    print("hello, world")
    time.sleep(1)
elif k==3:
    print("Halo, word!!!")
    time.sleep(1)
elif k==4:
    print("世界，您好！")
    time.sleep(1)
elif k==5:
    print("https://zerojudge.tw/ShowProblem?problemid=a001")
    time.sleep(1)
```
:::

## g

### g216
```python=
print("2^(10^{})".format(input()))
```

### g275
```python=
n = int(input())
for i in range(n):
    couplet1 = list(map(int, input().split()))
    couplet2 = list(map(int, input().split()))
    viola = []
    if couplet1[1] == couplet1[3] or couplet1[1] != couplet1[5] or couplet2[1] == couplet2[3] or couplet2[1] != couplet2[5]:
        viola.append("A")
    if couplet1[6] != 1 or couplet2[6] != 0:
        viola.append("B")
    if couplet1[1] == couplet2[1] or couplet1[3] == couplet2[3] or couplet1[5] == couplet2[5]:
        viola.append("C")
    if not viola:
        print("None\n")
    else:
        print(''.join(viola))
        print('\n')
```

### g384
```python=
print(sum(map(lambda x: ord(x)-ord('A')+1, input())))
```

### g496
```python=
a,b = map(int,input().split())
if b/a%1>0:print(b//a+1)
else:print(b//a)
```

## h

### h213
```python=
print('357389824')
```

### h280
```python=
print(input()+input())
```

### h631
```python=
def t():
    n = int(input())
    while n % 2 == 0:
        n //= 2
    while n % 3 == 0:
        n //= 3
    while n % 5 == 0:
        n //= 5
    if n == 1:
        print('ugly')
    else:
        print('beautiful')
t()
```

## i

:::danger
### i213
```python=
n = int(input())
stack = []
for _ in range(n):
    command = input().split()
    k = int(command[0])
    if k == 1:
        x = int(command[1])
        stack.append(x)
    elif k == 2:
        if stack:
            print(stack[-1])
        else:
            print(-1)
    elif k == 3:
        if stack:
            stack.pop()
```
:::

### i399
```python=
from collections import Counter
L=[int(x) for x in input().split()]
a=Counter(L).most_common()
print(a[0][1],end=' ')
b=sorted(set(L),reverse=True)
for i in b:
    print(i,end=' ')
```

## j

### j605
```python=
n = int(input())
ohno = 0
alltime = []
scoreall = []
for i in range(n):
    t, s = map(int, input().split())
    alltime.append(t)
    scoreall.append(s)
    if s < 0:
        ohno += 1
all_score = max(scoreall)-n-(ohno*2)
if allscore < 0:
    allscore = 0
print(allscore, alltime[scoreall.index(max(scoreall))])
```

## k

### k200
```python=
print(max([int(input()),int(input()),int(input())]))
```

### k402
```python=
n = int(input())
if n>2:
    n-=2
else:
    if n==1:
        print(0)
    else:
        print(0,1)
nums = [0,1]
for i in range(n):
    nums.append(nums[i]+nums[i+1])
total = nums[-1]
print(total)
```

## n

### n763
:::danger
```python=
from collections import deque
def odd_killer(n, numbers):
    queue = deque(numbers)
    while len(queue) > 1:
        current = queue.popleft()
        if current % 2 == 0:
            queue.popleft()
        queue.append(current)
    return queue[0]
n = int(input().strip())
numbers = list(map(int, input().strip().split()))
result = odd_killer(n, numbers)
print(result)
```
:::

## o

### o076
```python=
n=int(input())
h=list(map(int, input().split()))
longst=1
long=1
rh=h[0]
for i in range(1,n):
    if rh>h[i]:
        long+=1
        longst=max(longst,long)
    else:
        long=1
    rh=h[i]
print(longst)
```

### o087
:::spoiler 太長了，請點開看
```python=
def Evaluate(Name: str):
    if(type(Name) != str):
        return -1
    Score = 0
    NameLen = len(Name)
    for i in range(NameLen):
        CharCode = ord(Name[i])
        Score += ((CharCode * 1123) % 1002)
        while (CharCode > 0):
            Score += (CharCode % 10)
            CharCode = (CharCode // 10)            
    return (Score % 101)
n = int(input())
name_list = []
for i in range(n):
    name = input()
    score = Evaluate(name)
    name_list.append((name, score))
sorted_name_list = sorted(name_list, key=lambda x: x[1])
for i in sorted_name_list:
    print(i[0], i[1])
```
:::

## 自訂的現成 $function$

### 各種$sort$
#### $Bubble$ $Sort$
```python
def bubble_sort(numbers):
    n = len(numbers)
    for i in range(n):
        for j in range(0,(n-i-1)):
            if numbers[j] > numbers[j+1]:
                numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
    return numbers
```

#### $Selection$ $Sort$
```python=
def selection_sort(numbers):
    for i in range(len(numbers)):
        idx = i
        for j in range(i,len(numbers)):
            if numbers[j] < numbers[idx]:
                idx = j
        numbers[i], numbers[idx] = numbers[idx], numbers[i]
    return numbers
```

#### $Insertion$ $Sort$
```python=
def insertion_sort(numbers):
    n = len(numbers)
    for i in range(1, n):
        key = numbers[i]
        j = i - 1
        while j >= 0 and numbers[j] > key:
            numbers[j + 1] = numbers[j]
            j -= 1
        numbers[j + 1] = key
    return numbers
```
```python=
def insertion_sort(numbers):
    for i in range(1, len(numbers)):
        for j in range(i-1, -1, -1):
            if numbers[i]>numbers[j]:
                a = numbers.pop(i)
                numbers.insert(j+1, a)
                break
            if j==0:
                a = numbers.pop(i)
                numbers.insert(0, a)
    return numbers
```

#### $Quick$ $Sort$
```python=
def quick_sort(numbers):
    if len(numbers) <= 1:
        return numbers
    pivot = numbers[len(numbers) // 2]
    left = [x for x in numbers if x < pivot]
    middle = [x for x in numbers if x == pivot]
    right = [x for x in numbers if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)
```
```python=
def qsort(nums):
    if len(nums) <= 1:
        return nums
    a = nums[0]
    right = []
    left = []
    for num in nums[1:]:
        if num < a:
            left.append(num)
        elif num >= a:
            right.append(num)
    return qsort(left) + [a] + qsort(right)
```

#### $Merge$ $Sort$
```python=
def merge_sort(numbers):
    if len(numbers) <= 1:
        return numbers
    mid = len(numbers) // 2
    left = merge_sort(numbers[:mid])
    right = merge_sort(numbers[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result
```