APCS 從考題到專題

113學年度高雄中學 | 程式設計培訓增能計畫

張老師

2024年11月09日(六)

14:00 ~ 17:00

  • Python基礎結構操作
  • APCS選題實作
  • 視窗程式專題入門

Selection(選擇) - 選擇式(分支或選擇結構)

比較運算子

條件式: 項目一 比較運算 項目二 (條件成立 True / 條件不成立 False)

  • ==: 是否相等
  • !=: 是否不相等
  •  >: 大於
  • >=: 大於等於
  •  <: 小於
  • <=: 小於等於
  • 邏輯運算子

  • and: 連接 2 個條件。所有條件成立才為 True
  •  or: 連接 2 個條件。任一條件成立即為 True
  • 4種if區段結構

    if 和 elif 都必須接條件式

    • (1) if
    • (2) if-else
    • (3) if-elif... (可以有多個 elif)
    • (4) if-elif...else

    if區段

                
                print("Beebo: Let's hang out.")
                weather = input("How is the weather? ")
                if weather == "sunny":
                    print("(1) Sure. Why not?")
                
            

    if-else區段

                
                print("Beebo: Let's hang out.")
                weather = input("How is the weather? ")
                if weather == "sunny":
                    print("(1) Sure. Why not?")
                else:
                    print("(2) I want to stay home.")
                
            

    if-elif...區段

    可以有多個 elif,都必須接條件式

                
                print('L.Left')
                print('R.Right')
                print('U.Up')
                print('D.Down')
                op = input('> ').upper()
                # 依選項輸出方向
                if op == 'L':
                    print('Left')
                elif op == 'R':
                    print('Right')
                elif op == 'U':
                    print('Up')
                elif op == 'D':
                    print('Down')
                
            

    if-elif...else區段

                
                print('L.Left')
                print('R.Right')
                print('U.Up')
                print('D.Down')
                op = input('> ').upper()
                # 依選項輸出方向
                if op == 'L':
                    print('Left')
                elif op == 'R':
                    print('Right')
                elif op == 'U':
                    print('Up')
                elif op == 'D':
                    print('Down')
                else:
                    print('Wrong direction')
                
            

    APCS實作分數與級分

                
                score = int(input("Score: "))
    
                if score >= 350 and score <= 400:
                    level = 5
                elif score >= 250 and score <= 349:
                    level = 4
                elif score >= 150 and score <= 249:
                    level = 3
                elif score >= 50 and score <= 149:
                    level = 2
                elif score >= 0 and score <= 49:
                    level = 1
    
                print(level)
                
            

    Repetition(重複) - for loop迴圈式(迴圈或重複結構)

    for迴圈結構

    • for 迴圈變數 in 一堆數據:
    • 每次迴圈,從一堆數據中讀取一個,存到迴圈變數
    • 迴圈變數,不一定要在迴圈中使用
    • 數據讀完,就離開迴圈

    限定步數

                
                for i in range(7):
                    print(f'#{i}')
                    print('L.Left')
                    print('R.Right')
                    print('U.Up')
                    print('D.Down')
                    op = input('> ').upper()
                    # 依選項輸出方向
                    if op == 'L':
                        print('Left')
                    elif op == 'R':
                        print('Right')
                    elif op == 'U':
                        print('Up')
                    elif op == 'D':
                        print('Down')
                    else:
                        print('Wrong direction')
                
            

    Repetition(重複) - while loop迴圈式(迴圈或重複結構)

    任意步數

                
                while True:
                    print('L.Left')
                    print('R.Right')
                    print('U.Up')
                    print('D.Down')
                    print('Q.Quit')
                    op = input('> ').upper()
                    # 依選項輸出方向或離開
                    if op == 'Q':
                        break
                    elif op == 'L':
                        print('Left')
                    elif op == 'R':
                        print('Right')
                    elif op == 'U':
                        print('Up')
                    elif op == 'D':
                        print('Down')
                    else:
                        print('Wrong direction')
                
            

    一維與二維

    一維轉二維

                
                rows = 4
                cols = 3
                nums = rows * cols
                # 一維轉二維
                for i in range(nums):
                    ri = i // cols
                    ci = i % cols
                    print(f'{i} -> ({ri}, {ci})')
                
            

    二維轉一維

                
                rows = 4
                cols = 3
                nums = rows * cols
                # 二維轉一維
                for ri in range(rows):
                    for ci in range(cols):
                        i = ri * cols + ci
                        print(f'({ri}, {ci}) -> {i}')
                
            

    一維亂數存到二維

                
                import random
                random.seed(1)
                rows = 4
                cols = 3
                # 一維串列
                alist = list(range(1, rows*cols+1))
                print(*alist)
                print()
                # 洗牌
                random.shuffle(alist)
                print('1D-list')
                print(*alist)
                print()
                # 一維亂數存到二維
                atable = []
                for ri in range(rows):
                    arow = []
                    for ci in range(cols):
                        arow.append(alist[ri*cols+ci])
                    atable.append(arow)
                print('2D-table')
                for row in atable:
                    print(*row)
                
            

    二維亂數存到一維

                
                import random
                random.seed(1)
                rows = 4
                cols = 3
                # 一維串列
                nlist = list(range(1, rows*cols+1))
                print(*nlist)
                print()
                # 二維亂數串列
                atable = []
                for ri in range(rows):
                    arow = []
                    for ci in range(cols):
                        # 從一維串列隨機選取一數存到二維中的一列
                        arow.append(nlist.pop(random.randrange(len(nlist))))
                    atable.append(arow)
                print('2D-table')
                for row in atable:
                    print(*row)
                print()
                # 串列合併
                alist = []
                for row in atable:
                    alist = alist + row
                print('1D-list')
                print(*alist)
                print()
                
            

    函式

    歐式距離

                
                import math
    
                def get_distance(x1, y1, x2, y2):
                    return math.sqrt((x1-x2)**2 + (y1-y2)**2)
    
                point1 = list(map(int, input().split()))
                point2 = list(map(int, input().split()))
                x1, y1 = point1
                x2, y2 = point2
                print(get_distance(x1, y1, x2, y2))
                
            

    自訂整數亂數函式

    完成 get_randint 函式功能

                
                import random
    
                def get_randint():
                    return random.random()
    
                for i in range(10):
                    print(get_randint())
                
            

    矩陣題選題

    炸彈偵測器

    測資生成

                
                import random
    
                R, C = list(map(int, input().split()))
                for ri in range(R):
                    for ci in range(C):
                        rnum = random.randint(1, 5)
                        if rnum in (1, 5):
                            print(rnum, end=' ')
                        else:
                            print(0, end=' ')
                    print()
                
            

    輸入範例5

                
                10 10
                0 1 5 0 0 0 0 0 0 0
                5 0 0 0 1 5 0 0 0 0
                1 0 0 0 0 0 0 0 5 0
                0 0 1 0 0 0 0 5 0 0
                0 0 5 0 5 0 1 0 0 0
                0 0 0 0 1 0 5 0 0 0
                0 1 5 0 5 0 0 0 1 5
                0 0 0 1 0 0 0 0 0 0
                1 0 0 5 5 1 0 0 0 0
                5 0 0 0 0 0 0 1 5 0
                
            

    輸入範例5(試算用)

                
                0,1,5,0,0,0,0,0,0,0
                5,0,0,0,1,5,0,0,0,0
                1,0,0,0,0,0,0,0,5,0
                0,0,1,0,0,0,0,5,0,0
                0,0,5,0,5,0,1,0,0,0
                0,0,0,0,1,0,5,0,0,0
                0,1,5,0,5,0,0,0,1,5
                0,0,0,1,0,0,0,0,0,0
                1,0,0,5,5,1,0,0,0,0
                5,0,0,0,0,0,0,1,5,0
                
            

    半成品

    失效偵測器

                
                R, C = list(map(int, input().split()))
                atable = []
                for ri in range(R):
                    arow = list(map(int, input().split()))
                    atable.append(arow)
    
                for arow in atable:
                    print(*arow)
                
            

    視窗程式專題

    基本視窗

                
                from random import randint
                from tkinter import *
                from tkinter.font import Font
    
                class Application(Frame):
                    def __init__(self, master, N):
                        super().__init__(master)
                        self.master.title('Detector')
                        self.N = N
                        self.R = N-2
                        self.C = N-2
    
                        width = N*36
                        height = N*36 + 100
                        x = (self.master.winfo_screenwidth() // 2) - (width // 2)
                        y = (self.master.winfo_screenheight() // 2) - (height // 2)
                        self.master.resizable(False, False)
                        self.master.geometry('{}x{}+{}+{}'.format(width, height, x, y))
    
                        self.master.grid_columnconfigure([i for i in range(N)], weight=1)
                        self.appfont = Font(family='Consolas', size=12)
                        self.values = [['0']*N for i in range(N)]
                        self.atable = []
                        self.idx = 0
                        self.set_values()
                        self.set_widgets()
                        self.bind_functions()
    
                    def set_values(self):
                        pass
    
                    def change_cell(self, acell):
                        pass
    
                    def set_widgets(self):
                        myfont = self.appfont
                        mytk = self.master
                        N = self.N
    
                        for ri in range(N):
                            arow = []
                            for ci in range(N):
                                acell = Button(mytk, text=self.values[ri][ci], font=myfont,
                                               width=3, relief='solid', borderwidth=1,
                                               bg='#cccccc', fg='#000000')
                                acell.grid(row=ri, column=ci, sticky=NSEW, padx=2, pady=2)
                                if ri != 0 and ri != N-1 and ci != 0 and ci != N-1:
                                    self.change_cell(acell)
                                arow.append(acell)
                            self.atable.append(arow)
    
                        self.run1 = Button(mytk, text='Check detectors', font=myfont, width=3,
                                    relief='solid', borderwidth=1)
                        self.run1.grid(row=N+1, columnspan=N, sticky=NSEW, padx=2, pady=2)
                        self.run2 = Button(mytk, text='Check bombs', font=myfont, width=3,
                                    relief='solid', borderwidth=1)
                        self.run2.grid(row=N+2, columnspan=N, sticky=NSEW, padx=2, pady=2)
    
                    def bind_functions(self):
                        self.run1['command'] = self.check_detectors
                        self.run2['command'] = self.check_bombs
    
                    def check_detectors(self):
                        pass
    
                    def check_bombs(self):
                        pass
    
    
                N = randint(5, 10) + 2
                N = 7 + 2
                print(f'N: {N-2}')
                app = Application(master=Tk(), N=N)
                app.mainloop()
                
            

    參考書