Skip to content

Latest commit

 

History

History
63 lines (44 loc) · 1.99 KB

Cows-and-bulls(4digits).md

File metadata and controls

63 lines (44 loc) · 1.99 KB

11.4: Bulls and Cows (4 digits)

The Problem

Create a bulls and cows game for guessing a randomly generated 4 digits number.

Hints

This one should be easier for you. Just make sure that the random number is four digits. Hence, it should be between 1000 and 9999.

To calculate the bulls and cows,

Solution

importrandomsecret_number=str(random.randint(1000, 9999)) print("Guess the number. It contains 4 digits.") remaining_try=7defget_bulls_cows(number, user_guess): bulls_cows= [0,0] #cows, then bullsforiinrange(len(number)): ifuser_guess[i] ==number[i]: bulls_cows[0] +=1elifuser_guess[i] innumber: bulls_cows[1] +=1returnbulls_cowswhileremaining_try>0: player_guess=input("Enter your guess: ") ifplayer_guess==secret_number: print("Yay, you guessed it!") print("YOU WIN.") breakelse: bulls_cows=get_bulls_cows(secret_number,player_guess) print("Bulls: ",bulls_cows[0]) print("Cows: ",bulls_cows[1]) remaining_try-=1ifremaining_try<1: print("You lost the game.") break

Try it on Programming Hero

Explanation

After solving the Bulls and cows for 2 digits, this one should become easier for you.

However, solving this one by using if-else that we did for 2 digit bulls and cows game will become very harder.

That's why we created the get_bulls_cows function. Inside that, we created a loop. For each digit, check the digit in the same place.

  Next Page  

tags: programming-heropythonpython3problem-solvingprogrammingcoding-challengeinterviewlearn-pythonpython-tutorialprogramming-exercisesprogramming-challengesprogramming-fundamentalsprogramming-contestpython-coding-challengespython-problem-solving

close