wonderbeyond
9/2/2014 - 1:39 PM

## Rider and Rogue logic problem

Rider and Rogue logic problem

``````#!/usr/bin/python
# coding=utf-8
'''

'''

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'不',
))
``````