Created
February 27, 2017 22:42
-
-
Save y1n0/9d8f7b05b5435ffdaa1ba8b05d91551e to your computer and use it in GitHub Desktop.
practicepython.org's ex #18
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python3.5 | |
| import random | |
| def main(): | |
| # the random number is in form of list | |
| num = [random.randint(0, 9) for i in range(4)] | |
| tries = 0 | |
| print(num) | |
| while True: | |
| cows = 0 | |
| bulls = 0 | |
| guess = input('enter your guess: ') | |
| while len(guess) != 4: | |
| guess = input('please enter exactly 4 digit: ') | |
| # the guessed number is submitted as str, then it is | |
| # transformed to list of ints | |
| guess = [int(i) for i in guess] | |
| # cows or bulls? | |
| for i in enumerate(guess): | |
| if i[1] in num: | |
| if i[1] == num[i[0]]: | |
| cows += 1 | |
| else: | |
| bulls += 1 | |
| print('cows: ', cows, 'bulls: ', bulls) | |
| tries += 1 | |
| if cows == 4: | |
| print('it took you', tries, 'to correctly guess the number') | |
| break | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
excellent solution. Could you explain why enumerate was used. Could be done using range. Any specific use for enumerate??