# Create a program that will play the “cows and bulls” game with the user. # Randomly generate 4 digit number. import random complist = '123456789' compnum = random.sample(complist, 4) compnum = list(map(int, compnum)) # To convert string array to int array since above makes a string list # print(compnum) # This shows your final output def userinput(): userinp = input("Please enter a 4 digit number: ") if len(userinp) < 4 or len(userinp) > 4: print("The value should be <> 4") userinput() else: userinp = [int(i) for i in str(userinp)] # This converts the number to a list format print(userinp) checkdigits(userinp, compnum) def checkdigits(userinp, compnum): bull_count = 0 cow_count = 0 for i in range(0, len(compnum)): if compnum[i] == userinp[i]: bull_count += 1 for j in range(0, len(userinp)): if compnum[i] == userinp[j] and i != j: cow_count += 1 if bull_count == 4: print("Congrats! Correct guess!") exit() elif cow_count >= 0 or bull_count >= 0: print("You have " + str(cow_count) + " cows and " + str(bull_count) + " bulls! Try again..? Y/N") tryagain = input() if tryagain.lower() == 'y': userinput() else: quit() userinput()
I had a really really hard time figuring this one out. Honestly. There was a point where I just wanted to give up and mostly because I’m not well versed with lists. I was not aware that you could simple “array-fy” it and compare index values present in the list.