Skip to content

Instantly share code, notes, and snippets.

@wcp1231
Last active April 6, 2017 08:29
Show Gist options
  • Save wcp1231/5746244 to your computer and use it in GitHub Desktop.
Save wcp1231/5746244 to your computer and use it in GitHub Desktop.
豆瓣小组里的一道题目:随机一个四位数(四数字互不重复)让游戏者去猜,猜的数字中某一位猜对记做一个A,如果游戏者提交的数字中有数字属于被猜数字中的一个但位置不对则记为B。如 生成的数学为:1234 猜 9241 返回 1A2B 猜5678 返回0A0B 拿来练手练手。
import random
all_number = [str(i) for i in range(1, 10)]
get_number_A = lambda p, g: len(filter(lambda x: x[0] == x[1], zip(p, g)))
get_number_B = lambda p, g: len(filter(lambda x: x in p, g))
puzzle = random.sample(all_number, 4)
guess = list(raw_input())
number_A = get_number_A(puzzle, guess)
number_B = get_number_B(puzzle, guess) - number_A
while number_A < 4:
print 'Sorry, %dA%dB' % (number_A, number_B)
guess = list(raw_input())
number_A = get_number_A(puzzle, guess)
number_B = get_number_B(puzzle, guess) - number_A
print 'Bingo! %s' % ''.join(puzzle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment