Cows and Bulls Write a PYTHON program that plays the Cows an
Cows and Bulls. Write a PYTHON program that plays the Cows and Bulls game. The game works as follows. Randomly generate a 3-digit number, where every digit between 0 and 9 is unique. Ask the user to guess a 3-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, report the number of “cows” and “bulls”. Once the user guesses the correct number, the game is over.
A code has been provided for you. It contains two user-defined functions: main() and welcome(). The main() function drives the program. The welcome() function prints a welcome message to the screen. The code for the welcome() function has been provided for you. Your goal is to write the remaining part of the main() function.
The code:
import random
def welcome():
print(\'-----------------------------\')
print( \'| Welcome to Cows and Bulls |\')
print( \'-----------------------------\')
print()
def main():
welcome()
# Write the rest of code here.
main()
Please try to explain the steps as much as you could.
Programming tips. When generating a 3-digit random number, make sure that every digit is unique. The best way to do this to keep generating a random number until the digits are unique.
Note that since the program uses random number, your program will not run in the same manner as the following examples unless the same random numbers are generated.
Solution
import random
def welcome():
print(\'-----------------------------\')
print( \'| Welcome to Cows and Bulls |\')
print( \'-----------------------------\')
print(\'\')
def main():
welcome()
lis = [0,1,2,3,4,5,6,7,8,9]
n = []
temp = random.randrange(len(lis))
n.append(lis[temp])
lis = lis[0:temp] + lis[temp+1:]
temp = random.randrange(len(lis))
n.append(lis[temp])
lis = lis[0:temp] + lis[temp+1:]
temp = random.randrange(len(lis))
n.append(lis[temp])
lis = lis[0:temp] + lis[temp+1:]
#print(n)
ss = \"\".join(str(eg) for eg in n)
count = 1
cow = 0
bull = 0
while(cow!=3):
#print(),
cow = 0
bull = 0
inp = int(raw_input(\'Guess #\'+str(count)+\':\'))
inp_list = []
inp_list.append(inp%10)
inp = inp/10
inp_list.append(inp%10)
inp = inp/10
inp_list.append(inp%10)
inp = inp/10
inp_list.reverse()
#print(inp_list)
for i in range(0,3):
if(inp_list[i] in n):
if(inp_list[i]==n[i]):
cow = cow + 1
else:
bull = bull + 1
print(str(cow) + \' cows, \'+str(bull)+\' bulls.\')
count = count + 1
count = count - 1
print(\'You got it!\')
print(\'It took you \'+str(count)+\' guesses to find the secret number \'+ss+\'.\')
# Write the rest of code here.
main()

