總習題
習題一
請把一篇英文文章(不限字數)存入一個名為input.txt的檔案,並寫一支程式算出a-z各字母分別出現多少個。
觀看解答
file = open("input.txt") #開啟檔案 alpha = "abcdefghijklmnopqrstuvwxyz " #建立搜尋目標 desk = [] #建立陣列 for x in range(len(alpha)): desk.append(0) #初始陣列的值 for lines in file: #一次讀一行 for chars in lines : #每行中一次讀一個字元 for i in range(len(alpha)): #比對每個搜尋目標 if chars ==alpha[i]: #如果與目標相同 desk[i] += 1 #該目標紀錄+1 break #跳出一層迴圈 file.close() #關閉檔案 for i in range(len(alpha)): #把每筆結果印出來 print("'" + str(alpha[i]) + "'" + " = " + str(desk[i]))習題二
請製作一個4*4的賓果遊戲:由程式隨機產生一個4*4的賓果盤,再由使用者一一輸入中獎號碼,直到出現直、橫、斜連線,則輸出「Bingo!」,並結束遊戲。
請製作一個4*4的賓果遊戲:由程式隨機產生一個4*4的賓果盤,再由使用者一一輸入中獎號碼,直到出現直、橫、斜連線,則輸出「Bingo!」,並結束遊戲。
觀看解答
import random # 載入隨機函數 number_all = [] # 用於儲存賓果盤 line = [] # 用於儲存每條線尚未中獎的數字個數 Bingo = 1 # 用於判斷是否連線的變數 # 將數字1~16放進number_all for i in range(1,17): number_all.append(i) # 洗牌 random.shuffle(number_all) # 印出賓果盤,每4個數字換行 for j in range(16): print(number_all[j], end="\t") if j%4 ==3: print("\n") # 將每條線尚未中獎的數字個數預設為4 for k in range(10): line.append(4) while(Bingo != 0): # 當尚未連線則執行 # 由使用者輸入中獎號碼 choice = input("中獎號碼:") print() #換行 # 若中獎號碼在某直排 for check_column in range(4): if(number_all.index(int(choice)) % 4 == check_column): line[check_column] -= 1 # 若中獎號碼在某橫排 for check_row in range(4): if(number_all.index(int(choice)) // 4 == check_row): line[check_row+4] -= 1 # 若中獎號碼在斜排 if(number_all.index(int(choice)) == 0): line[8] -= 1 elif(number_all.index(int(choice)) % 5 == 0): line[8] -= 1 elif(number_all.index(int(choice)) % 3 == 0): line[9] -= 1 # 在中獎號碼前方添加*符號 number_all[number_all.index(int(choice))] = "*" + str(number_all[number_all.index(int(choice))]) # 印出新的賓果盤 for j in range(16): print(number_all[j], end="\t") if j%4 ==3: print("\n") # 判斷是否連線(若連線則變數Bingo == 0) for l in range(10): Bingo *= line[l] print("Bingo!") # 連線後不繼續執行迴圈則印出「Bingo!」習題三
請設計一個選擇左右邊的遊戲,一開始輸入要挑戰的層數,然後會出現選擇左右的圖,再使用random來隨機排列出解答,最後詢問要不要重新挑戰,範例如下所示:
>>>
輸入挑戰層數:4
|\ 選擇左右邊(L/R):L
x
你輸了
是否重新挑戰(Y/N):Y
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):R
x
你輸了
是否重新挑戰(Y/N):Y
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):L
|
|\ 選擇左右邊(L/R):L
|
O
恭喜勝利
是否重新挑戰(Y/N):N
>>>
請設計一個選擇左右邊的遊戲,一開始輸入要挑戰的層數,然後會出現選擇左右的圖,再使用random來隨機排列出解答,最後詢問要不要重新挑戰,範例如下所示:
>>>
輸入挑戰層數:4
|\ 選擇左右邊(L/R):L
x
你輸了
是否重新挑戰(Y/N):Y
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):R
x
你輸了
是否重新挑戰(Y/N):Y
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):R
|
|\ 選擇左右邊(L/R):L
|
|\ 選擇左右邊(L/R):L
|
O
恭喜勝利
是否重新挑戰(Y/N):N
>>>
觀看解答
from random import randint import string def GetLR(): # get L/R char sLR = "L" # default set to L iRandomNumber = randint(1, 10) # get random number from 1 to 10 if ((iRandomNumber % 2) == 0): # let even number be set to R sLR = "R" # set to R return(sLR) def GetCap(sIn): # transform to cap return(string.capwords(sIn)) while (True): # forever game loop while (True): # if not input number, then input forever bBreak = True # set break flag try: iLevel = int(input("輸入挑戰層數:")) # set level except ValueError: print("[注意]請輸入數字...") bBreak = False # set not to break finally: if (bBreak == True): break iCount = 0 # set current level while (iCount < iLevel): # check whether complete the game sSpace = "" # set default level space to null for i in range(iCount): # set level indent space sSpace += " " sGuess = GetCap(input(sSpace + "|\\選擇左右邊(L/R):")) sAnswer = GetLR() # get random L/R from function if (sGuess == sAnswer): # compare answer print(sSpace + "|") if (iCount == (iLevel - 1)): # check whether meet max level print(sSpace + "O") # print okay print("恭喜勝利") else: print("X") # print bomb print("你輸了") break iCount += 1 # count level up while (True): # check if replay game sAgain =GetCap(input("是否重新挑戰(Y/N):")) if (sAgain == "Y") or (sAgain == "N"): break # break only Y/N/y/n if (sAgain == "Y"): # if Y/y, then replay game continue elif (sAgain == "N"): # if N/n, then bye-bye print("遊戲結束,Bye bye") break習題4
請寫出一支能將所輸入之十進位數值轉換成特定進位數結果的程式,例如: 設定為2進位,且輸入的值為20,程式將會輸出10100。
請寫出一支能將所輸入之十進位數值轉換成特定進位數結果的程式,例如: 設定為2進位,且輸入的值為20,程式將會輸出10100。
觀看解答
while(1): base = input("請輸入進位基底:") if(int(base) <= 35 and int(base) > 1): break print("基底數範圍為 2~35") num = input("請輸入要轉換的數:") tmp = "" #儲存已經算出來的部分 tm_num = int(num) #將要算的數存起來 base_over = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" while(tm_num > 0 ): #如果還有沒處理的部分 #除掉基底數後的餘數為目前結果的最高位數 if(tm_num % int(base) > 9): #超過10進位後的表示法有ABCD... tmp = base_over[(tm_num % int(base))-10] + tmp else: tmp = str(tm_num % int(base)) + tmp tm_num = tm_num // int(base) #留下剩餘的部分 print(base + "進位的" + num + "為: " + tmp) #印出結果習題5
請讓使用者輸入一個數字,再將此數字進行質因數分解。
請讓使用者輸入一個數字,再將此數字進行質因數分解。
觀看解答
number = int(input("請輸入數字:")) factor = [] factor_times = [] for i in range(2, number+1): for j in range(2, int(i**0.5)+2): if (i % j == 0 and i != 2): break if (j == int(i**0.5)+1): if (number%i == 0): factor.append(i) times = 0 while (number%i == 0): times += 1 number //= i factor_times.append(times) for k in range(len(factor)): print("%d^%d" % (factor[k], factor_times[k]), end='') if (k != len(factor)-1): print("*", end='')習題6
請讓使用者輸入一串密碼,再檢驗該密碼是否為六個字以上,其中至少要包含一個大寫英文字母、一個小寫英文字母與一個阿拉伯數字。
請讓使用者輸入一串密碼,再檢驗該密碼是否為六個字以上,其中至少要包含一個大寫英文字母、一個小寫英文字母與一個阿拉伯數字。
觀看解答
password = input("請輸入密碼:") sL = bL = n = 0 if (len(password) >= 6): for i in range(len(password)): if (password[i].islower()): sL = 1 if (password[i].isupper()): bL = 1 if (password[i].isdigit()): n = 1 if (sL*bL*n): print("True") else: print("False") else: print("False")習題7
設計一個加密演算法,讓使用者輸入一句英文語句,然後將句中每個字母換成其反序的字母後輸出,例如,A↔Z、B↔Y、C↔X、…。
設計一個加密演算法,讓使用者輸入一句英文語句,然後將句中每個字母換成其反序的字母後輸出,例如,A↔Z、B↔Y、C↔X、…。
觀看解答
password = input("請輸入欲加密文字:") sL = "abcdefghijklmnopqrstuvwxyz" bL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(len(password)): if (password[i].islower()): for j in range(26): if (password[i] == sL[j]): print(sL[25-j], end='') else: for k in range(26): if (password[i] == bL[k]): print(bL[25-k], end='')習題8
選舉的「棄保效應」源自於中國象棋術語「棄車保帥」,意思為放棄次要的棋子以保主要棋子的安全。現在有三位候選人A、B及C,請利用隨機函數賦予各個候選人一個2000~4000間的值當作其民調結果:假設投票當天棄保效應發酵,原本支持排名最後候選人的選民有35%將改投民調第二的候選人,而其餘選民的投票則仍與原民調結果相同。請輸出各個候選人的民調結果與實得票數,並顯示得最高票者為當選人。
選舉的「棄保效應」源自於中國象棋術語「棄車保帥」,意思為放棄次要的棋子以保主要棋子的安全。現在有三位候選人A、B及C,請利用隨機函數賦予各個候選人一個2000~4000間的值當作其民調結果:假設投票當天棄保效應發酵,原本支持排名最後候選人的選民有35%將改投民調第二的候選人,而其餘選民的投票則仍與原民調結果相同。請輸出各個候選人的民調結果與實得票數,並顯示得最高票者為當選人。
觀看解答
import random poll = [random.randint(2000, 4000), random.randint(2000, 4000), random.randint(2000, 4000)] print("民意調查: A-%d票, B-%d票, C-%d票" % (poll[0], poll[1], poll[2])) mid = [0, 1, 2] mid.remove(poll.index(min(poll))) mid.remove(poll.index(max(poll))) final = poll final[mid[0]] += int(min(poll)*0.35) final[poll.index(min(poll))] -= int(min(poll)*0.35) print("投票結果: A-%d票, B-%d票, C-%d票" % (final[0], final[1], final[2])) name = ["A", "B", "C"] print("由%s當選" % name[poll.index(max(poll))])觀看解答
birthplace = {"A":10,"B":11,"C":12,"D":13,"E":14,"F":15,"G":16,"H":17,"I":34,"J":18,"K":19,"L":20,"M":21,"N":22,"O":34,"P":23,"Q":24,"R":25,"S":26,"T":27,"U":28,"V":29,"W":32,"X":30,"Y":31,"Z":33} idNumber = input("請輸入身分證字號:") sum = int(str(birthplace[idNumber[0]])[0]) + int(str(birthplace[idNumber[0]])[1])*9 for i in range(1,9): sum += int(idNumber[i])*(9-i) sum += int(idNumber[9]) if (sum%10 == 0): print("有效") else: print("無效")習題10
撰寫一支程式,讓使用者輸入一個100以內的正整數當作金額,再計算後輸出該金額有多少種硬幣組合方式。其中,硬幣面值為1元、5元、10元及50元等四種。
撰寫一支程式,讓使用者輸入一個100以內的正整數當作金額,再計算後輸出該金額有多少種硬幣組合方式。其中,硬幣面值為1元、5元、10元及50元等四種。