Skip to content

Instantly share code, notes, and snippets.

@y1n0
Created February 27, 2017 22:42
Show Gist options
  • Select an option

  • Save y1n0/9d8f7b05b5435ffdaa1ba8b05d91551e to your computer and use it in GitHub Desktop.

Select an option

Save y1n0/9d8f7b05b5435ffdaa1ba8b05d91551e to your computer and use it in GitHub Desktop.
practicepython.org's ex #18
#!/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()
@gauravpatt92
Copy link

gauravpatt92 commented May 4, 2017

excellent solution. Could you explain why enumerate was used. Could be done using range. Any specific use for enumerate??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment