CS50_AI_1_Konwledge 推理 (Python实现-中文注释)

根据已有信息推理未知信息

下面的代码实现的功能是:
根据 harry.py 在Knowledge 提供的信息, 构建一个库, 然后 你给出询问的信息,
它会将根据库中信息, 进行命题的逻辑推理, 最后得到询问信息的 真假情况

由于本人的Python刚学几天, 一些代码实现细节并不是很清楚, 希望大佬看的时候可以的话 提一下意见 (逃

调用方式

创建两个文件, 然后命名为一下名称, 然后在 harry.py 点击运行就好啦~

harry.py

from logic import *

# Create new classes, each having a name, or a symbol, representing each proposition.
rain = Symbol("rain")  # It is raining.
hagrid = Symbol("hagrid")  # Harry visited Hagrid
dumbledore = Symbol("dumbledore")  # Harry visited Dumbledore

# Save sentences into the KB
knowledge = And(  # Starting from the "And" logical connective, becasue each proposition represents knowledge that we know to be true.

    # 不下雨就去拜访 Hagrid
    Implication(Not(rain), hagrid),  # ¬(It is raining) → (Harry visited Hagrid)

    # 或者 两个都有可能被拜访: 两者的并集
    Or(hagrid, dumbledore),  # (Harry visited Hagrid) ∨ (Harry visited Dumbledore).

    # 不可能两个都去拜访: 两者的交集
    Not(And(hagrid, dumbledore)),  # ¬(Harry visited Hagrid ∧ Harry visited Dumbledore) i.e. Harry did not visit both Hagrid and Dumbledore.

    # 哈利去找邓布利多 
    dumbledore  # Harry visited Dumbledore. Note that while previous propositions contained multiple symbols with connectors, this is a proposition consisting of one symbol. This means that we take as a fact that, in this KB, Harry visited Dumbledore.
    )

print(model_check(knowledge, rain)) # 根据构建出来的知识工程来判断 "rain" 状态的真假:也就是通过上面的情况来推断下雨的真假(所以这里是可以换成其他滴~)

logic.py

import itertools

class Sentence():

    def evaluate(self, model):
        """Evaluates the logical sentence."""
        raise Exception("nothing to evaluate")

    def formula(self):
        """Returns string formula representing logical sentence."""
        return ""

    def symbols(self):
        """Returns a set of all symbols in the logical sentence."""
        return set()

    @classmethod
    def validate(cls, sentence):
        if not isinstance(sentence, Sentence): # 判断两个句子是不是相同的类型
            raise TypeError("must be a logical sentence")

    @classmethod
    def parenthesize(cls, s):
        """Parenthesizes an expression if not already parenthesized."""
        def balanced(s):
            """Checks if a string has balanced parentheses."""
            count = 0
            for c in s:
                if c == "(":
                    count += 1
                elif c == ")":
                    if count <= 0:
                        return False
                    count -= 1
            return count == 0
        if not len(s) or s.isalpha() or (
            s[0] == "(" and s[-1] == ")" and balanced(s[1: -1])
        ):
            return s
        else:
            return f"({
     s})"


class Symbol(Sentence):

    def __init__(self, name)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值