自然三元逻辑?

时间:2012-02-15 15:17:40

标签: python logic

  

可能重复:
  How can I find the missing value more concisely?

是否有一种很好的方法可以使用Python语言在字母T a b上表达交换运算符c,其中

  • a T b == c
  • b T c == a
  • c T a == b

我最好的尝试是硬编码:

def T(first, second):
    if first is 'a' and second is 'b':
        return 'c'
    if first is 'a' and second is 'c':
        return 'c'
    if first is 'b' and second is 'c':
        return 'a'
    if first is 'b' and second is 'a':
        return 'c'
    if first is 'c' and second is 'a':
        return 'b'
    if first is 'c' and second is 'b':
        return 'a'

5 个答案:

答案 0 :(得分:10)

这个怎么样:

alphabet = set(['a', 'b', 'c'])
def T(x, y):
    return (alphabet - set([x, y])).pop()

像这样使用它:

T('a', 'b')
> 'c'

答案 1 :(得分:3)

l = ['a', 'b', 'c']
return list(set(l) - set((first, second)))[0]

答案 2 :(得分:3)

这是一个定义运算符'|'的Python类这样你就可以写'a' |T| 'b'并得到你得到的'c':

class Ternary(object):
    def __init__(self, *items):
        if len(items) != 3:
            raise ValueError("must initialize with exactly 3 items")

        self.items = set(items)
        self.left = None

    def __ror__(self, other):
        ret = Ternary(*list(self.items))
        ret.left = other
        return ret

    def __or__(self, other):
        if self.left is not None:
            ret = (self.items-set([self.left,other])).pop()
            return ret
        else:
            raise ValueError("cannot process right side without left side")

T = Ternary('a', 'b', 'c')
for test in """'a' |T| 'c'
               'a' |T| 'b'
               'c' |T| 'b'""".splitlines():
    test = test.strip()
    print test, '->', eval(test)

打印:

'a' |T| 'c' -> b
'a' |T| 'b' -> c
'c' |T| 'b' -> a

答案 3 :(得分:1)

>>> def T(first, second):
...     s = ord('a') + ord('b') + ord('c')
...     return chr(s - ord(first) - ord(second))
... 
>>> T('a', 'b')
'c'

答案 4 :(得分:1)

查找表怎么样:

def T(first, second):
   d={'ab':'c',
      'ac':'c',
      'bc':'a',
      'ba':'c',
      'ca':'b',
      'cb':'a'}

      st=''.join([first,second])
      if d[st]: return d[st]
      else: return None