Python 入門指南 5.0
exercise2705.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | # 從 random 引入 shuffle from random import shuffle # 猜數字遊戲 class Guess: # 建構子 def __init__(self, length): self.length = length self.set_answer() # 字串形式 def __str__(self): return str(self.answer) # 建立答案 def set_answer(self): # 建立數字串列 numbers = list("0123456789") # 利用迴圈讓答案的第一個數字不為 0 while numbers[0] == "0": # 攪亂數字串列 shuffle(numbers) # 猜數字遊戲答案的屬性 self.answer = "" i = 0 for c in numbers: self.answer += c i += 1 if i == self.length: break # 測試輸入是否有重複數字 def repeat_test(self, guess): # 將輸入轉換成集合 guess_set = set(guess) # 檢測重複數字 if len(guess_set) == self.length: return True else: return False # 計算 A 、 B 值 def find_AB(self, guess): # 將答案轉換成集合 answer_set = set(self.answer) # 回傳 A 、 B 值 if guess == self.answer: return str(self.length) + "A" else: i = A = B = 0 while i < self.length: if guess[i] == self.answer[i]: A += 1 else: if guess[i] in answer_set: B += 1 i += 1 return str(A) + "A" + str(B) + "B" # 執行部分 if __name__ == '__main__': # 建立遊戲答案 g = Guess(6) # 印出猜數字遊戲的答案 print(g.answer) # 檢測是否有重複數字 print(g.repeat_test("123456")) # 檢測 A 、 B 值 print(g.find_AB("123456")) # 檔名: exercise2705.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 11 月 |