授業動画
項目
- random
- int
- list
- hit
- blow
最初
./python_codes/c5_hit_and_blow/c5_hit_and_blow_init.py
1 import random
2
3 a = random.randint(0,9)
4 print(a)
5
6 b = int(input("数をいれてね>"))
7 print(b)
8
9 if a==b:
10 print("hit")
11 else:
12 print("miss")
最終
./python_codes/c5_hit_and_blow/c5_hit_and_blow.py
1 import random
2 random.seed(0)
3 a = [random.randint(0, 9),
4 random.randint(0, 9),
5 random.randint(0, 9),
6 random.randint(0, 9)]
7 a = [0,1,6,0]
8 print(a)
9 print(str(a[0])+str(a[1])+str(a[2])+str(a[3]))
10
11 while True:
12 isok = False
13 while isok == False:
14 b = input("数を入れてね>")
15 if len(b) !=4:
16 print("4桁の数字をいれてね")
17 else:
18 kazuok = True
19 for i in range(4):
20 if ((b[i]<"0") or (b[i]>"9")):
21 print("b["+str(i)+"]は数字ではありません.")
22 kazuok = False
23 break
24 else:
25 isok = True
26
27 hit = 0
28 for i in range(4):
29 if a[i] == int(b[i]):
30 hit = hit + 1
31 print("hit:"+str(hit))
32
33 blow = 0
34 for j in range(4):
35 for i in range(4):
36 if (int(b[j])==a[i]) and (int(b[i])!=a[i]) and(int(b[j])!=a[j]):
37 blow = blow + 1
38 break
39
40 print("blow:"+str(blow))
41
42 if hit == 4:
43 print("当たり")
44 break
45
46 exit()
blow判定注意
バグ発見.
blow = 0
for j in range(4):
for i in range(4):
if (int(b[j])==a[i]) and (int(b[i])!=a[i]) and(int(b[j])!=a[j]):
blow = blow + 1
break
だと,randomで作った数字が
[0,1,6,0]
に対して
[6,6,1,0]
と予測した場合に,
hit:1 blow:3
と判断される.正しくは,
hit:1 blow:2
でないとだめ.
- 重複した数字を選ばないようにするか,
- はたまた,より厳密にblowを判断させるか...
より厳密なblow判定をさせるのは以下の通り.意外とめんどい.もっと楽なやり方があれば教えてください.
./python_codes/c5_hit_and_blow/c5_blow_rev.py
1 a = [0, 1, 6, 0]
2 b = [6, 6, 1, 0]
3 hit = 1
4 blow = 0
5 a1 = sorted(a)
6 b1 = sorted(b)
7 print("sorted_a=", a1)
8 print("sorted_b=", b1)
9 i = 0
10 j = 0
11 print('b', 'i', 'j', 'a_i', 'b_i')
12 while True:
13 print(blow, i, j, a1[i], b1[j])
14 if int(b1[j]) == int(a1[i]):
15 blow += 1
16 i += 1
17 j += 1
18 else:
19 if int(b1[j]) > int(a1[i]):
20 i += 1
21 else:
22 j += 1
23 if i == 4 or j == 4:
24 break
25
26
27 print("blow:"+str(blow-hit))
- source ~/Desktop/Lectures/lecture_22s/CompA/c5_hit_and_blow_text.org