Last active
August 29, 2015 14:05
-
-
Save wonderbeyond/5a555b294e67e02ce08f to your computer and use it in GitHub Desktop.
Rider and Rogue logic problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| # coding=utf-8 | |
| ''' | |
| 一个岛上居住着两类人——骑士和流氓。骑士说的都是真话,而流氓总是说谎。 | |
| 现在碰到了岛上的两个人A和B,如果A说“B是骑士”,B说“我们两人不是一类人”。 | |
| 请判断A、B两人到底是骑士还是流氓。 | |
| ''' | |
| class Speaker(object): | |
| '''说话人, 可能是A, 也可能是B''' | |
| @classmethod | |
| def build(self, v): | |
| '''根据代号构造两种身份: 0代表骑士, 1代表流氓''' | |
| return Rider() if v == 0 else Rogue() | |
| def judge_b(self): | |
| '''作为A, 根据他是否说实话, 判断B的身份''' | |
| return Rider() if self.say_truth else Rogue() | |
| def judge_a(self): | |
| '''作为B, 根据他是否说实话, 判断A的身份''' | |
| return Rogue() if self.say_truth else Rogue() | |
| def same_sort_with(self, o): | |
| '''判断对方和自己是否同类人''' | |
| return o.__class__ is self.__class__ | |
| class Rider(Speaker): | |
| '''骑士''' | |
| say_truth = True | |
| @property | |
| def sort(self): | |
| return u'骑士' | |
| class Rogue(Speaker): | |
| '''流氓''' | |
| say_truth = False | |
| @property | |
| def sort(self): | |
| return u'流氓' | |
| for a, b in [(0, 1), (0, 0), (1, 1), (1, 0)]: | |
| a, b = Speaker.build(a), Speaker.build(b) | |
| #判断推导出来的身份是否与当前的假设冲突 | |
| no_conflict = a.judge_b().same_sort_with(b) and b.judge_a().same_sort_with(a); | |
| print (u'假设: A是%s, B是%s, 则推导出: B是%s, A是%s, *%s冲突*, 所以假设 *%s成立*' % | |
| (a.sort, b.sort, | |
| a.judge_b().sort, b.judge_a().sort, | |
| u'无' if no_conflict else u'有', | |
| u'' if no_conflict else u'不', | |
| )) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment