Des détails supplémentaires basés sur ce que j'ai trouvé ici et là comme je cherchais un opérateur d'implication: vous pouvez utiliser un astucieux bidouillage pour définir vos propres opérateurs. Voici un exemple en cours annoté avec des sources qui m'amènent à ce résultat.
#!/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)
Et c'est plus simple que (x et y) ou pas x. Merci –
La TTL est d'accord - mais ce n'est pas nécessairement si facile à voir dans le code, bien que plus simple que l'original. Une fonction - c'est-à-dire 'implique (x, y)' - pourrait aider à transférer davantage l'idée, si une telle construction se produit assez souvent pour justifier un nom. – user2246674
@ user2246674 D'accord, je recommanderais d'en faire une fonction pour plus de clarté. –