Python 入門指南 5.0
exercise2704.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 | # 從 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
# 執行部分
if __name__ == '__main__':
# 建立遊戲答案
g = Guess(4)
# 印出猜數字遊戲的答案
print(g.answer)
# 檢測是否有重複數字
print(g.repeat_test("1123"))
# 檔名: exercise2704.py
# 說明:《Python入門指南》的練習
# 網站: http://kaiching.org
# 作者: 張凱慶
# 時間: 2023 年 11 月
|