Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
simple and nonoptimal solution in Clear category for Bulls and Cows by cimarronm
from itertools import permutations
def is_possible_seq(seq, guess, response):
bulls = sum(a==b for a, b in zip(seq, guess))
cows = len(set(seq) & set(guess)) - bulls
return response == (bulls, cows)
def checkio(data):
# non-optimal
# picks out a valid possibility given the guesses and responses so far
possible = set(permutations(range(10), 4))
# sucessively eliminate possibilities based upon the guess and response
for result in data:
guess, response = result.split()
guess = tuple(int(c) for c in guess)
response = int(response[0]), int(response[2])
possible = {seq for seq in possible if is_possible_seq(seq, guess, response)}
# pick one of the possibilites left as next guess
return "".join(str(digit) for digit in possible.pop())
if __name__ == '__main__':
#This part is using only for self-checking and not necessary for auto-testing
def check_solution(func, goal):
recent = []
for step in range(8):
user_result = func(recent)
bulls = cows = 0
for u, g in zip(user_result, goal):
if u == g:
bulls += 1
elif u in goal:
cows += 1
recent.append("{0} {1}B{2}C".format(user_result, bulls, cows))
if bulls == 4:
print("{0} Win with {1} steps.".format(goal, step + 1))
return True
print("{0} Fail.".format(goal))
return False
assert check_solution(checkio, "1234"), "1234"
assert check_solution(checkio, "6130"), "6130"
assert check_solution(checkio, "0317"), "0317"
assert check_solution(checkio, "9876"), "9876"
April 22, 2015
Comments: