自然三进制逻辑?

3
这可能是一个重复的问题:
如何更简洁地查找缺失值? 用Python语言表达字母表a、b、c上的可交换运算符T是否有优雅的方式,其中:
  • 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'

请定义“可交换三元运算符T”的要求。它有什么作用? - Steven Rumbalski
可交换的:对于任何 i,j,都有 i T j == j T i。三元的:“在字母表 a,b,c 上”。 - Randomblue
2
这是你想要的吗?https://dev59.com/F2oy5IYBdhLWcg3wEKBn - ChessMaster
4
比较字符串时不要使用“is”,而应该使用“==”。 - user395760
2
你想要 "a T a"、"b T b" 和 "c T c" 具有什么值? - Edward Loper
@Randomblue:因为它不可靠,至少目前是这样的。请参考https://dev59.com/F3A75IYBdhLWcg3w_uqD(请注意,对于整数也是如此,小的整数可能会被缓存,但通常情况下您可以拥有多个相等值的整数对象)。 - user395760
5个回答

10
这个怎么样:
alphabet = set(['a', 'b', 'c'])
def T(x, y):
    return (alphabet - set([x, y])).pop()

这样使用:

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

你定义的 T('a','c') 产生了 'b' 而不是 OP 在他的例子中定义的 'c'?这只是他的例子中的错误吗? - the wolf
1
@carrot-top 我认为这个示例中有一个错误。 - Óscar López

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

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接