Chi tiết bổ sung dựa trên những gì tôi đã tìm thấy ở đây và ở đó khi tôi đang tìm kiếm nhà điều hành ngụ ý: bạn có thể sử dụng thông minh để xác định nhà khai thác của riêng mình. Đây là một ví dụ đang chạy được chú thích với các nguồn dẫn tôi đến kết quả này.
#!/usr/bin/python
# From http://code.activestate.com/recipes/384122/ (via http://stackoverflow.com/questions/932328/python-defining-my-own-operators)
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
from itertools import product
booleans = [False,True]
# http://stackoverflow.com/questions/16405892/is-there-an-implication-logical-operator-in-python
# http://jacob.jkrall.net/lost-operator/
operators=[
(Infix(lambda p,q: False), "F"),
(Infix(lambda p,q: True), "T"),
(Infix(lambda p,q: p and q), "&"),
(Infix(lambda p,q: p or q) , "V"),
(Infix(lambda p,q: p != q) , "^"),
(Infix(lambda p,q: ((not p) or not q)), "nad"),
(Infix(lambda p,q: ((not p) and not q)), "nor"),
(Infix(lambda p,q: ((not p) or q)), "=>"),
]
for op,sym in operators:
print "\nTruth tables for %s" % sym
print "\np\tq\tp %s q\tq %s p" % (sym,sym)
for p,q in product(booleans,repeat=2):
print "%d\t%d\t%d\t%d" % (p,q,p |op| q,q |op| p)
print "\np\tq\tr\tp %s q\tq %s r\t(p %s q) %s r\tp %s (q %s r)\tp %s q %s r" % (sym,sym,sym,sym,sym,sym,sym,sym)
for p,q,r in product(booleans,repeat=3):
print "%d\t%d\t%d\t%d\t%d\t%d\t\t%d\t\t%d" % (p,q,r,p |op| q,q |op| r, (p |op| q) |op| r, p |op| (q |op| r), p |op| q |op| r)
assert((p |op| q) |op| r == p |op| q |op| r)
Và đó là đơn giản hơn (x và y) hoặc không x. Cảm ơn –
TTL đồng ý - nhưng nó không nhất thiết phải dễ dàng nhìn thấy trong mã, mặc dù đơn giản hơn so với bản gốc. Một hàm - tức là 'ngụ ý (x, y)' - có thể giúp chuyển ý tưởng hơn, nếu một cấu trúc như vậy xảy ra thường đủ để đảm bảo một tên. – user2246674
@ user2246674 Đồng ý, tôi khuyên bạn nên thực hiện chức năng này để làm rõ. –