【问题标题】:Natural ternary logic? [duplicate]自然三元逻辑? [复制]
【发布时间】:2012-03-06 22:45:36
【问题描述】:

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

有没有一种使用 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”的要求。它有什么作用?
  • 交换:i T j == j T i 代表任何i, j。三元:“在字母表上a, b, c
  • stackoverflow.com/questions/8792440/…这是你想要的吗?
  • 不要使用is 比较字符串。使用==
  • 您希望“a T a”、“b T b”和“c T c”具有哪些值?

标签: python logic


【解决方案1】:

这个怎么样:

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'?这只是他的例子中的一个错误吗???
  • @carrot-top 我认为这是示例中的错误
【解决方案2】:
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
    

    【讨论】:

      【解决方案4】:
      >>> def T(first, second):
      ...     s = ord('a') + ord('b') + ord('c')
      ...     return chr(s - ord(first) - ord(second))
      ... 
      >>> T('a', 'b')
      'c'
      

      【讨论】:

        【解决方案5】:

        查找表怎么样:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-21
          • 2021-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-27
          • 2012-08-07
          相关资源
          最近更新 更多