簡體   English   中英

Python dict使用邏輯輸入的真值表

[英]Python dict using logic input for truth tables

好吧,男孩和女孩在這里我們走了。 首先,我有兩個問題。 由於我的程序很大,所以我將分階段提出問題,這是第一個問題。 我正在創建一個為后綴邏輯表達式生成真值表的程序。 以下是允許的運算符及其邏輯等效項:

Operators:
=                Logical Equivalence (≡ or ↔) 
`->` or `<=`     Logical Implication (→)
+                Disjunction (∨), AKA “or”
*                Conjunction (∧), AKA “and” 
`~` or `!`       Negation (¬), AKA “not”

以下是一些輸入和輸出示例:

input
p True =

output
p      p True =
False  False
True   True

input
p !

output
p      p !
False  True
True   False

input
p q =

output
p      q      p q =
False  False  True
False  True   False
True   False  False
True   True   True

好的,我真的不知道從哪里開始,但是我並沒有要求任何人為我編寫該程序。 我知道我需要使用Python字典編寫代碼,該字典將鍵與相應的命題相匹配。 但是,我怎么知道要為鍵放置哪些值呢? 另外,在以下情況下:

`->` or `<=`     Logical Implication (→)

`~` or `!`       Negation (¬), AKA “not”

如何分配2個不同的輸入以便可以在python字典中使用? 我希望這不要太令人困惑,我對python非常了解,希望能對您有所幫助。 謝謝!

更新好,這是我現在擁有的代碼:

propositions = {
    '=' : (2, {(True, True): True,
              (True, False): False,
              (False, True) : False,
              (False, False): True,
              }),
    '->' : (2, {(True, True): True,
                (True, False): False,
                (False, True): True,
                (False, False): True,
                }),
    '+' : (2, {(True, True): True,
               (True, False): True,
               (False, True): True,
               (False, False): False,
               }),
    '*' : (2, {(True, True): True,
               (True, False): False,
               (False, True): False,
               (False, False): False,
               }),
    '!' : (1, {True: False,
               False: True})}

prop = sys.stdin.readline()
prop = prop.split()
prop = prop[::-1]
for x in prop:

我相信我成功地反轉了字符串並刪除了所有空格,但是對於遍歷它仍然有些困惑。

第二次更新是我的代碼:

propositions = {
    '=' : (2, {(True, True): True,
              (True, False): False,
              (False, True) : False,
              (False, False): True,
              }),
    '->' : (2, {(True, True): True,
                (True, False): False,
                (False, True): True,
                (False, False): True,
                }),
    '+' : (2, {(True, True): True,
               (True, False): True,
               (False, True): True,
               (False, False): False,
               }),
    '*' : (2, {(True, True): True,
               (True, False): False,
               (False, True): False,
               (False, False): False,
               }),
    '!' : (1, {True: False,
               False: True})}

prop = sys.stdin.readline()
prop = prop.strip().split()
prop = reversed(prop)
def evaluate():
    token = next(prop)
    try:
        nargs, table = propositions[token]
    except KeyError:
        if token.lower() in ('true', '1'):
            return True
        elif token.lower() in ('false', '0'):
            return False
        else:
            return token
    return table[tuple(evaluate() for i in range(nargs))]

您必須按照從外到內的解析順序構建字典:

master_dict = {
   '=': (2, {(True, True): True,
             (True, False): False,
             ...
             }),
   ...
   '!': (1, {True: False,
             False: True})}

數字表示操作員要使用的操作數。

要解析輸入,請從右向左讀取。

使用遞歸函數,該函數從右側消耗一個令牌。

(1)如果令牌是運算符(即字典中的鍵),則從主字典中檢索相應的值。

首先存儲的數字是運算符采用的參數數。 因此,您的函數現在必須根據參數調用自身的次數。 確保跟蹤已讀取的令牌。 一種精巧的方法是使用列表迭代器,該迭代器將只吐出每個元素一次,因此您不會出錯。 一旦有了所有參數,就應用剛剛檢索的真值表,讀出結果並返回。

(2)如果令牌不是操作者,則您的函數必須將其返回。

prop = sys.stdin.readline()

def solve_no_var(prop):
    rev_iter = reversed(prop)
    def evaluate():
        token = next(rev_iter)
        try:
            nargs, table = propositions[token]
        except KeyError:
            if token.lower() in ('true', '1'):
                return True
            elif token.lower() in ('false', '0'):
                return False
            else:
                return token
        return table[tuple(evaluate() for i in range(nargs))]
    return evaluate()

def solve(prop):
    prop = prop.strip().split()
    variables = list(set(prop) - set(propositions)
        - {'True', 'TRUE', 'true', '1', 'False', 'FALSE', 'false', '0'})
    lookup = {v: [j for j, p in enumerate(prop) if p == v] for v in variables}
    N = len(variables)
    print((N*" {:6} ").format(*variables), 'result')
    for p in itertools.product(("True", "False"), repeat=N):
        prop_nv = prop.copy()
        for v, b in zip (variables, p):
            for j in lookup[v]:
                prop_nv[j] = b
        res = solve_no_var(prop_nv)
        print(((N+1)*" {:6} ").format(*(p + (res,))))

solve(prop)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM