Cows and Bulls is a code-breaking game that tests logical thinking and deduction skills. In this game, the computer generates a secret 4-digit number with unique digits, and the player attempts to guess it. After each guess, the program provides hints in the form of bulls and cows, helping the player narrow down the correct number.
Working of the Game
- Generate a Secret Number: The program creates a random 4-digit number with no repeated digits.
- Accept User Guesses: The player enters a 4-digit guess.
- Compare Digits: The guess is compared with the secret number.
- Count Bulls: Digits that match in both value and position are counted as bulls.
- Count Cows: Digits that exist in the secret number but are in the wrong position are counted as cows.
- Repeat Until Success: The game continues until the player guesses the correct number or runs out of attempts.
Example:
Let's see a sample run for better understanding.
Secret Code: 3768
Guess: 1234
Response: 0 bulls, 1 cow
Guess: 5678
Response: 1 bull, 2 cows
Guess: 1678
Response: 1 bull, 2 cows
Guess: 3678
Response: 2 bulls, 2 cows
Guess: 3148
Response: 2 bulls, 0 cows
Guess: 3768
You guessed right!
Algorithm
- Generate a random 4-digit number with unique digits.
- Ask the user for the maximum number of attempts.
- Accept a 4-digit guess from the user.
- Validate that the guess contains unique digits.
- Compare the guess with the secret number.
- Count bulls and cows based on digit matches.
- Display the result after each guess.
- End the game when all digits match or attempts are exhausted.
Program
# Import required module
import random
# Returns list of digits
# of a number
def getDigits(num):
return [int(i) for i in str(num)]
# Returns True if number has
# no duplicate digits
# otherwise False
def noDuplicates(num):
num_li = getDigits(num)
if len(num_li) == len(set(num_li)):
return True
else:
return False
# Generates a 4 digit number
# with no repeated digits
def generateNum():
while True:
num = random.randint(1000,9999)
if noDuplicates(num):
return num
# Returns common digits with exact
# matches (bulls) and the common
# digits in wrong position (cows)
def numOfBullsCows(num,guess):
bull_cow = [0,0]
num_li = getDigits(num)
guess_li = getDigits(guess)
for i,j in zip(num_li,guess_li):
# common digit present
if j in num_li:
# common digit exact match
if j == i:
bull_cow[0] += 1
# common digit match but in wrong position
else:
bull_cow[1] += 1
return bull_cow
# Secret Code
num = generateNum()
while True:
try:
tries = int(input("Enter number of tries: "))
break
except ValueError:
print("Please enter a valid number.")
# Play game until correct guess
# or till no tries left
while tries > 0:
try:
guess = int(input("Enter your guess: "))
except ValueError:
print("Please enter a valid 4-digit number.")
continue
if not noDuplicates(guess):
print("Number should not have repeated digits. Try again.")
continue
if guess < 1000 or guess > 9999:
print("Enter 4 digit number only. Try again.")
continue
bull_cow = numOfBullsCows(num,guess)
print(f"{bull_cow[0]} bulls, {bull_cow[1]} cows")
tries -=1
if bull_cow[0] == 4:
print("You guessed right!")
break
else:
print(f"You ran out of tries. Number was {num}")
Output:

Explanation:
- Generate Secret Code: The generateNum() function creates a random 4-digit number with unique digits.
- Validate Digits: The noDuplicates() function checks whether a number contains repeated digits.
- Convert Number to Digits: The getDigits() function converts a number into a list of its digits.
- Count Bulls and Cows: The numOfBullsCows() function compares the secret number and the guess to calculate bulls and cows.
- Process User Guesses: A loop repeatedly accepts guesses and validates the input.
- Display Result: The game displays the number of bulls and cows after each attempt and ends when the secret number is guessed.
Time Complexity Analysis
- Time Complexity: O(1) since the game always works with fixed 4-digit numbers.
- Space Complexity: O(1) because only a small fixed number of variables and lists are used.