Programming
My finished code for each week's homework.
Learning materials
Week 1
Week 2
Week 35 problems
1A001Am I an adult?Easy
1000 ms128.0 KBDescription
Read an age. If it isn't a number, print an error message; if it is, decide whether the person is an adult.
Input
Enter the age as an integer.
Output
If the input isn't a number, print 請輸入正確年齡 ("please enter a valid age"). If it is a number and >= 18, print 成年 ("adult"); if it is < 18, print 未成年 ("minor").
Sample input #1abc
Sample output #1請輸入正確年齡
Sample input #216
Sample output #2未成年
Sample input #3100
Sample output #3成年
#我有成年嗎 age = input("請輸入年齡:")#只接受整數 try: age = int(age) if age >= 18: print("成年") else: print("未成年") except ValueError:#防爆程式 print("請輸入正確年齡")2C004Score to letter gradeEasy
1000 ms64.0 KBDescription
Read an integer score from 0 to 100
Print the matching letter grade90–100: A
80–89: B
70–79: C
60–69: D
0–59: EInput
Read an integer score from 0 to 100
Output
Print the matching letter grade
Sample input #190
Sample output #1A
Sample input #250
Sample output #2E
#分數等第 grd = input("請輸入成績:") try: grd = int(grd) if grd >= 90: print(f"A") elif grd >= 80: print(f"B") elif grd >= 70: print(f"C") elif grd >= 60: print(f"D") else: print(f"E") except ValueError: print(f"請輸入正確數值")3A002Is it a leap year?Easy
1000 ms128.0 KBDescription
Read a year and decide whether it is a leap year.
Leap year rule: divisible by 4 but not by 100, or divisible by 400.
Input
Read the year as an integer
Output
Leap year: print 今年是閏年 ("this year is a leap year")
Not a leap year: print 今年不是閏年 ("this year is not a leap year")
Sample input #12001
Sample output #1今年不是閏年
Sample input #22024
Sample output #2今年是閏年
#今年是閏年嗎 year = input("請輸入整數年份") try: year = int(year) if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): print("今年是閏年") else: print("今年不是閏年") except ValueError: print("請輸入正確數值")4A003Can these sides form a triangle?Hard
1000 ms128.0 KBDescription
Read three side lengths and decide whether they can form a triangle.
Rule: the sum of any two sides must be greater than the third side. Check that all three inputs are numbers.
Input
Read three numbers. First check they are numbers, then check whether they can form a triangle.
Output
Triangle: print 可以組成三角形 ("can form a triangle")
Not a triangle: print 不能組成三角形 ("cannot form a triangle")
Anything else: print 請輸入正確數字 ("please enter valid numbers")Sample input #15 6 7
Sample output #1可以組成三角形
Sample input #25 6 abc
Sample output #2請輸入正確數字
#可以組成三角形嗎 try: a = float(input("請輸入第一邊長數值:")) b = float(input("請輸入第二邊長數值:")) c = float(input("請輸入第三邊長數值:")) if a + b > c and b + c > a and c + a > b: print("可以組成三角形") else: print("不能組成三角形") except ValueError: print("請輸入正確數字")5P001Odd or even?Easy
1000 ms128.0 KBDescription
If the input contains any non-digit character (letters, symbols, a decimal point or a minus sign), print 請輸入正確的非負整數 ("please enter a valid non-negative integer"). Otherwise convert it to an integer: if it is 0, print 此數為零 ("the number is zero"); if it is divisible by 2, print 這是一個偶數 ("this is an even number"); otherwise print 這是一個奇數 ("this is an odd number").
Input
One line of text: it may be a number, a negative number, a decimal or ordinary letters.
Output
One line: the result of the check, or an error message.
Sample input #18
Sample output #1這是一個偶數
Sample input #20
Sample output #2此數為零
s = input("請輸入一個非負整數:").strip() if s.isdigit(): n = int(s) if n == 0: print("此數為零") elif n % 2 == 0: print("這是一個偶數") else: print("這是一個奇數") else: print("請輸入正確的非負整數")
Week 415 problems
1A004Print multiples of 3Easy
1000 ms128.0 KBDescription
Use a for loop to print the multiples of 3.
Input
input any number
Output
Print each number that is a multiple of 3.
Sample input #120
Sample output #13 6 9 12 15 18
#印出三的倍數 num = (input("請輸入一個數字:")) if num.isdigit(): s = int(num) for i in range(1,s+1): if i % 3 == 0: print(i) else: print("請輸入正確值")2A005Sum & averageMedium
1000 ms128.0 KBDescription
Keep reading numbers until 0 is entered, then print the sum and the average.
Input
One number per line, until 0 is entered
Output
After 0 is entered, print the total sum and the average.
Sample input #11 2 3
Sample output #16 2.0
#算出總和&平均 方法一 total = 0 count = 0 while True: num = int(input("請輸入數字(輸入 0 結束):")) if num == 0: break total += num count += 1 print(total) if count == 0: print(0) else: print(total / count)#算出總和&平均 方法二 nums = [] while True: num = int(input("請輸入數字(輸入 0 結束):")) if num == 0: break nums.append(num) print(sum(nums)) if len(nums) == 0: print(0) else: print(sum(nums) / len(nums))3A006Compute the sumEasy
1000 ms128.0 KBDescription
Read n and compute the sum 1 + 2 + … + n.
Input
One number
Output
Print the sum of 1 to n.
Sample input #15
Sample output #115
Sample input #23
Sample output #26
#計算總和 num = input("請輸入一個數字:") if num.isdigit(): num = int(num) print(sum(range(1, num + 1)))4A007Count vowelsHard
1000 ms128.0 KBDescription
Read a line of English text and count its vowels, ignoring case.
Input
A line of English text
Output
If the text contains vowels (a, e, i, o, u), print how many there are in total.
Sample input #1Python
Sample output #11
# 判斷母音 text = input("請輸入一串英文:") count = 0 for ch in text.lower(): if ch in "aeiou": count += 1 print(count)
Slide exercisesW04 Loops · Problems 1–4 are HW4, due before next class11 problems
1Use for to print every multiple of 3 from 1 to 20Warm-up
# 第 1 題(暖身):用 for 印出 1 到 20 之間所有 3 的倍數 for i in range(1, 21): if i % 3 == 0: print(i)2Read n and compute the sum from 1 to n
# 第 2 題:輸入 n,算出 1 加到 n 的總和 try: n = int(input("請輸入 n:")) except ValueError: print("輸入錯誤,請輸入整數") else: total = 0 for i in range(1, n + 1): total += i print("1 加到", n, "的總和是", total)3Keep reading numbers, stop at 0, then print the sum and average
Description
This is a simplified version of the project's main menu.
# 第 3 題:一直讀入數字,輸入 0 就停止,最後印出總和與平均 total = 0 count = 0 while True: num = float(input("請輸入數字(輸入 0 結束):")) if num == 0: break total += num count += 1 if count == 0: print("沒有輸入任何數字") else: print("總和:", total) print("平均:", total / count)4Read a line of text and count its vowels (ignoring case)Challenge
# 第 4 題(挑戰):輸入一串文字,數出裡面有幾個母音(不分大小寫) text = input("請輸入一串文字:") count = 0 for ch in text.lower(): if ch in "aeiou": count += 1 print("母音個數:", count)5Keep asking until the input is validYour turn
Description
Ask the user for their weight in kilograms (decimals allowed). If the input is invalid, show a hint and ask again until it is valid; finally print the weight. Use while True with break.
Input
Test with abc, a blank line, -5 and 62.5, in that order
Output
abc, blank: 請輸入正確 ("please enter a valid value")
-5: 體重必須大於 0 ("weight must be greater than 0")
62.5: 你的體重: 62.5 ("your weight: 62.5")while True: kgs = 0 while kgs <= 0: try: kgs = float(input("請輸入體重kg:")) except ValueError: print("請輸入正確") continue if kgs <= 0: print("體重必須大於 0") print("你的體重:", kgs)6Print the 7 times table, plus squares of even numbersYour turn
Description
Use for to print the 7 times table, from 7 x 1 = 7 to 7 x 9 = 63 — nine lines.
Extra challenge: print the squares of the even numbers from 1 to 9, i.e. 2, 4, 6 and 8.
Output
7 x 1 = 7
7 x 2 = 14
…
7 x 9 = 632 的平方是 4 ("the square of 2 is 4")
4 的平方是 16
6 的平方是 36
8 的平方是 64# 第 27 頁:7 的乘法表 for i in range(1, 10): print("7 x", i, "=", 7 * i)# 第 27 頁額外挑戰:1 到 9 中,偶數的平方 for i in range(2, 10, 2): print(i, "的平方是", i * i)7Sum and average of 1 to 10, then of the even numbersYour turn
Description
Loop over range(1, 11) with for to get the sum and average of the ten numbers 1 to 10. Print them as 總和是 XX,平均是 X.X ("the sum is XX, the average is X.X"), with the average rounded to one decimal place.
Extra challenge: do it again with only the even numbers — 2, 4, 6, 8 and 10, five numbers in all.
Output
總和是 55,平均是 5.5 ("the sum is 55, the average is 5.5")
總和是 30,平均是 6.0
# 第 38 頁:1 到 10 的總和與平均 total = 0 count = 0 for i in range(1, 11): total = total + i count = count + 1 print(f"總和是 {total},平均是 {total / count:.1f}")# 第 38 頁額外挑戰:只計算 1 到 10 的偶數 total = 0 count = 0 for i in range(2, 11, 2): total = total + i count = count + 1 print(f"總和是 {total},平均是 {total / count:.1f}")8Plain while, break and continueExtra
Description
Predict the output of the three loops and explain how they differ.
Output
break ends the whole loop as soon as n == 4, so 4 is never printed. continue skips the rest of the current pass (the print) when n == 3, but the loop keeps going — so only 3 is missing.
# 第 6、12、13 頁:比較一般 while、break 與 continue print("一般 while:") count = 1 while count <= 3: print("第", count, "次") count = count + 1 print("break:") n = 1 while n <= 9: if n == 4: break print(n) n = n + 1 print("continue:") n = 0 while n < 5: n = n + 1 if n == 3: continue print(n)9Count the capital P'sExtra
Description
Walk through "Python Programming" with for and count the capital P's.
Output
出現了 2 個大寫 P ("found 2 capital P's")
# 第 33 頁:計算大寫 P 的個數 count = 0 for ch in "Python Programming": if ch == "P": count = count + 1 print("出現了", count, "個大寫 P")10Find the maximum — even if every number is negativeExtra
Description
Keep reading integers until q is entered; print the largest one, or a message if there was no data.
This example assumes every input is a valid integer or q; integers may be negative or 0.
Sample input #1-3 -9 -5 q
Sample output #1最大的是 -3
Sample input #2q
Sample output #2沒有輸入任何數字
# 第 35-37 頁:找最大值;假設輸入合法整數或 q biggest = 0 count = 0 while True: s = input("請輸入整數(q 結束):").strip() if s == "q": break number = int(s) if count == 0 or number > biggest: biggest = number count = count + 1 if count == 0: print("沒有輸入任何數字") else: print("最大的是", biggest)11Times table with nested loopsExtra
Description
Generate a times table with two nested loops. Start with 1 to 3, as shown on the slides.
Output
Every time the outer i changes, the inner j runs all the way through: the multiplication print runs 3 × 3 = 9 times and the separator line is printed 3 times.
For the full 9 × 9 table, change both range(1, 4) to range(1, 10).
# 第 41 頁:兩層迴圈,依簡報示範 1 到 3 for i in range(1, 4): for j in range(1, 4): print(i, "x", j, "=", i * j) print("---")
Week 54 problems
1A008Fruit listEasy
1000 ms128.0 KBlistIndexingDescription
First create a fruit list: fruits = ["apple", "banana", "cherry", "grape", "orange"]
Read an index K and print the fruit at that index in the list. Indexes start at 0, so 0 is apple and 4 is orange. For example, when K = 2, print cherry.
Input
One line containing an integer K (0 ≤ K ≤ 4).
Output
One line: the name of the matching fruit.
Sample input #12
Sample output #1cherry
# 水果 list fruits = ["apple", "banana", "cherry", "grape", "orange"] # 防爆:不是整數、超出 0~4 都重新詢問 while True: try: k = int(input("請輸入編號 K(0~4):")) except ValueError: print("請輸入整數") continue if 0 <= k < len(fruits): break print("編號要在 0 到 4 之間") print(fruits[k])2A009Sum of matrix borderMedium
1000 ms128.0 KBlist2D arrayMatrixDescription
Given an n × m integer matrix, find the sum of all its border elements. The border is the first row, the last row, the first column and the last column. Count each element only once (don't add the corner elements twice). For example, in the 3 × 3 matrix 1 2 3 4 5 6 7 8 9, everything except the 5 in the middle is on the border, so the answer is 40.
Hint: read each row with input().split(). Each of the four corners is reached once by the first/last row and once by the first/last column, so be careful not to count them twice.
Input
The first line has two integers n and m (1 ≤ n, m ≤ 10). Each of the next n lines has m integers a (-100 ≤ a ≤ 100), separated by spaces.
Output
One line: the sum of the border elements.
Sample input #13 3 1 2 3 4 5 6 7 8 9
Sample output #140
# 矩陣邊界總和 # 防爆:n、m 要是 1~10 的整數;每一列要剛好 m 個 -100~100 的整數,不對就重打那一列 while True: try: n, m = map(int, input("請輸入 n 與 m(以空格分隔):").split()) except ValueError: print("請輸入兩個整數,以空格分隔") continue if 1 <= n <= 10 and 1 <= m <= 10: break print("n 與 m 要在 1 到 10 之間") matrix = [] for i in range(n): while True: try: row = [int(x) for x in input(f"請輸入第 {i + 1} 列的 {m} 個整數:").split()] except ValueError: print("只能輸入整數") continue if len(row) != m: print(f"這一列要剛好 {m} 個數字") elif any(a < -100 or a > 100 for a in row): print("每個數字要在 -100 到 100 之間") else: break matrix.append(row) # 只要在第一列、最後一列、第一行或最後一行就加一次,角落不會重複 total = 0 for i in range(n): for j in range(m): if i == 0 or i == n - 1 or j == 0 or j == m - 1: total += matrix[i][j] print(total)3A010Sort primes and non-primesEasy
1000 ms128.0 KBwhilebreaklistSortingPrimesDescription
Write a program that keeps reading integers (one per line) and stops at 0 (0 itself is not counted). Split the numbers into primes and non-primes: sort the primes from largest to smallest and the non-primes from smallest to largest. Print all the primes first, then all the non-primes, on a single line separated by single spaces.
Note: 1 is not a prime. For example, for the input 7 4 2 9 5 1 0 (one number per line), the primes are 7, 2 and 5 — largest first, 7 5 2; the non-primes are 4, 9 and 1 — smallest first, 1 4 9. So the output is 7 5 2 1 4 9.
Hint: put them in two lists, sort each one, then append them with a loop.
Input
One positive integer x per line (1 ≤ x ≤ 1000), ending with 0. There is at least one number before the 0, and no more than 100 numbers.
Output
One line: all the primes (largest first), then all the non-primes (smallest first), separated by single spaces, with no trailing space.
Sample input #17 4 2 9 5 1 0
Sample output #17 5 2 1 4 9
# 質數與非質數排序 primes = [] others = [] # 防爆:不是整數、超出 1~1000 都重新輸入;還沒有數字就輸入 0 不算結束;最多 100 個 while True: try: x = int(input("請輸入正整數(輸入 0 結束):")) except ValueError: print("請輸入整數") continue if x == 0: if len(primes) + len(others) == 0: print("至少要輸入一個數字") continue break if x < 1 or x > 1000: print("數字要在 1 到 1000 之間") continue if len(primes) + len(others) >= 100: print("已經有 100 個數字,請輸入 0 結束") continue is_prime = x >= 2 # 1 不是質數 d = 2 while d * d <= x: if x % d == 0: is_prime = False break d += 1 if is_prime: primes.append(x) else: others.append(x) primes.sort(reverse=True) # 質數由大到小 others.sort() # 非質數由小到大 result = [] for p in primes: result.append(p) for o in others: result.append(o) print(" ".join(str(v) for v in result))4A011Bubble sort swap count (ascending and descending)Medium
1000 ms128.0 KBlistSortingBubble sortDescription
Given N integers, use bubble sort to find: 1. the number of swaps needed to sort them in ascending order (smallest to largest); 2. the number of swaps needed to sort them in descending order (largest to smallest).
Bubble sort repeatedly compares neighbouring numbers. For ascending order, swap when the first is greater than the second; for descending order, swap when the first is less than the second. Equal numbers are never swapped, and only swaps that actually happen are counted. For example, 3 1 2 needs 2 swaps to become ascending (1 2 3) and 1 swap to become descending (3 2 1), so the output is 2 1.
Hint: use the improved bubble sort from class and add a counter for the swaps.
Input
The first line has an integer N (1 ≤ N ≤ 100). The second line has N integers a (-1000 ≤ a ≤ 1000), separated by spaces.
Output
One line with two integers: the number of swaps for ascending order and for descending order, separated by a space.
Sample input #13 3 1 2
Sample output #12 1
# 泡沫排序交換次數(升冪與降冪) # 防爆:N 要是 1~100 的整數;第二行要剛好 N 個 -1000~1000 的整數,不對就重打 while True: try: n = int(input("請輸入 N(1~100):")) except ValueError: print("請輸入整數") continue if 1 <= n <= 100: break print("N 要在 1 到 100 之間") while True: try: nums = [int(x) for x in input(f"請輸入 {n} 個整數(以空格分隔):").split()] except ValueError: print("只能輸入整數") continue if len(nums) != n: print(f"要剛好 {n} 個數字") elif any(a < -1000 or a > 1000 for a in nums): print("每個數字要在 -1000 到 1000 之間") else: break def bubble_swaps(data, ascending): a = data.copy() # 複製一份,升冪和降冪都從原本的順序開始排 swaps = 0 for i in range(len(a) - 1): swapped = False for j in range(len(a) - 1 - i): if ascending: need_swap = a[j] > a[j + 1] else: need_swap = a[j] < a[j + 1] if need_swap: # 相等的數不交換 a[j], a[j + 1] = a[j + 1], a[j] swaps += 1 swapped = True if not swapped: # 這一輪都沒交換,代表已經排好 break return swaps print(bubble_swaps(nums, True), bubble_swaps(nums, False))