Skip to content

Instantly share code, notes, and snippets.

@libert-xyz
Created January 25, 2016 02:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save libert-xyz/d7e86fa4fd4eb5a8f987 to your computer and use it in GitHub Desktop.
Save libert-xyz/d7e86fa4fd4eb5a8f987 to your computer and use it in GitHub Desktop.
#rschmidt@libert.xyz
#http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html
import random
def start():
num = input('Enter a 3 digit number: ')
return num
def game():
randNum = random.randrange(100,900)
att = 0
while True:
num = start()
cowbull = CowBull(num,randNum)
if cowbull['cow'] == 3:
print ('You Win, the number was: ',randNum, 'attempts: ', att)
break
else:
print ( 'cows',cowbull['cow'],'bulls',cowbull['bull'])
att = att + 1
def CowBull(num,randnum):
cowbull ={'cow':0,'bull':0}
randStr = str(randnum)
for i in range(len(num)):
if randStr[i] == num[i]:
cowbull['cow'] = cowbull['cow'] + 1
elif num[i] in randStr:
cowbull['bull'] = cowbull['bull'] + 1
return cowbull
if __name__ == '__main__':
game()
@dclay1983
Copy link

Instead of:
randNum = random.randrange(100,900)
try:
randNum = str(random.randrange(100,900))
This will allow you to remove:
randStr = str(randnum)
Also you should be more explicit in your call:
num = start()
Make it:
num = str(start())
I like polymorphism and encourage it, but if you plan to use implicit then you need to error test as sometimes though you should receive a str from input, you receive an int.

@mprat
Copy link

mprat commented Mar 9, 2016

Agreed with @dclay1983. Otherwise, looks great!

@idontreallywolf
Copy link

idontreallywolf commented May 20, 2016

instead of :
cowbull['cow'] = cowbull['cow'] + 1
use:
cowbull['cow'] += 1

do the same with bull

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