-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathExercise-18-Cows-And-Bulls.py
95 lines (78 loc) · 2.54 KB
/
Exercise-18-Cows-And-Bulls.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'''
Exercise 18: Cows And Bulls
Create a program that will play the “cows and bulls”
game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to
guess a 4-digit number. For every digit that the user
guessed correctly in the correct place, they have a
“cow”. For every digit the user guessed correctly in
the wrong place is a “bull.” Every time the user makes
a guess, tell them how many “cows” and “bulls” they
have. Once the user guesses the correct number, the
game is over. Keep track of the number of guesses the
user makes throughout teh game and tell the user at
the end.
Say the number generated by the computer is 1038. An
example interaction could look like this:
Welcome to the Cows and Bulls Game!
Enter a number:
>>> 1234
2 cows, 0 bulls
>>> 1256
1 cow, 1 bull
...
Until the user guesses the number.
'''
# Solution
def initiation():
"""
Set all the parameter needed.
Returns:
guess_log -- a empty list container of all the guesses.
answer -- a 4-digital number string of right answer.
"""
import random
print('Welcome to the Cows and Bulls Game!')
guess_log = ['']
answer = random.randint(0,9999)
answer = '{0:04d}'.format(answer)
return guess_log, answer
def get_guess(guess_log):
"""
Append a new guess to the previous log.
Arguments:
guess_log -- a list contain all the guess(es).
Returns:
guess_log -- a list contain all the guess(es).
"""
guess = input('Enter a number:')
guess_log.append(guess)
return guess_log
def compare(guess, answer):
"""
Compare guess and answer
Arguments:
guess -- a 4-digital number string of the guess.
answer -- a 4-digital number string of right answer.
Returns:
cow -- a number of the user guessed correctly in the correct place.
bull -- a number of the user guessed correctly in the wrong place.
"""
cow = 0
bull = 0
for i in range(len(guess)):
if guess[i] == answer[i]:
cow += 1
if guess[i] in answer:
bull += 1
bull = bull - cow
return cow, bull
def main():
guess_log, answer = initiation()
while guess_log[-1] != answer:
guess_log = get_guess(guess_log)
cow, bull = compare(guess_log[-1], answer)
print('{} cows, {} bulls'.format(cow, bull))
print('Your are right! After {} guess(es) you finally get it!\nYour logs:'.format(len(guess_log)-1), guess_log[1:])
if __name__ == "__main__":
main()