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

下面的代码实现的功能是:
根据 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.# 不下雨就去拜访 HagridImplication(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 itertoolsclass 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()@classmethoddef validate(cls, sentence):if not isinstance(sentence, Sentence): # 判断两个句子是不是相同的类型raise TypeError("must be a logical sentence")@classmethoddef parenthesize(cls, s):"""Parenthesizes an expression if not already parenthesized."""def balanced(s):"""Checks if a string has balanced parentheses."""count = 0for c in s:if c == "(":count += 1elif c == ")":if count <= 0:return Falsecount -= 1return count == 0if not len(s) or s.isalpha() or (s[0] == "(" and s[-1] == ")" and balanced(s[1: -1])):return selse:return f"({s})"class Symbol(Sentence):def __init__(self, name):self.name = namedef __eq__(self, other):# isinstance : 判断类型是否相同return isinstance(other, Symbol) and self.name == other.name # 类型相同 且 name相同def __hash__(self):return hash(("symbol", self.name)) # eg: 将rain的哈希值映射为 "true" def __repr__(self):return self.name # 重构: 可自行查阅资料, 鼠鼠水平不够, 看不懂, 感觉上是"将输出对象按__repr__"方法定义的格式显示def evaluate(self, model):try:return bool(model[self.name]) # 当前单个符号的真假情况except KeyError:raise EvaluationException(f"variable {self.name} not in model")def formula(self):return self.namedef symbols(self):return {self.name}# 定义Not的类
class Not(Sentence):def __init__(self, operand):Sentence.validate(operand)self.operand = operanddef __eq__(self, other):return isinstance(other, Not) and self.operand == other.operanddef __hash__(self):return hash(("not", hash(self.operand)))def __repr__(self):return f"Not({self.operand})"def evaluate(self, model):return not self.operand.evaluate(model)def formula(self):return "¬" + Sentence.parenthesize(self.operand.formula())def symbols(self):return self.operand.symbols()# 定义And的类
class And(Sentence):def __init__(self, *conjuncts):for conjunct in conjuncts:Sentence.validate(conjunct)self.conjuncts = list(conjuncts)def __eq__(self, other):return isinstance(other, And) and self.conjuncts == other.conjunctsdef __hash__(self):return hash(("and", tuple(hash(conjunct) for conjunct in self.conjuncts)))def __repr__(self):conjunctions = ", ".join([str(conjunct) for conjunct in self.conjuncts])return f"And({conjunctions})"def add(self, conjunct):Sentence.validate(conjunct)self.conjuncts.append(conjunct)def evaluate(self, model):return all(conjunct.evaluate(model) for conjunct in self.conjuncts)def formula(self):if len(self.conjuncts) == 1:return self.conjuncts[0].formula()return " ∧ ".join([Sentence.parenthesize(conjunct.formula())for conjunct in self.conjuncts])def symbols(self):return set.union(*[conjunct.symbols() for conjunct in self.conjuncts])# 定义Or的类
class Or(Sentence):def __init__(self, *disjuncts):for disjunct in disjuncts:Sentence.validate(disjunct)self.disjuncts = list(disjuncts)def __eq__(self, other):return isinstance(other, Or) and self.disjuncts == other.disjunctsdef __hash__(self):return hash(("or", tuple(hash(disjunct) for disjunct in self.disjuncts)))def __repr__(self):disjuncts = ", ".join([str(disjunct) for disjunct in self.disjuncts])return f"Or({disjuncts})"def evaluate(self, model):return any(disjunct.evaluate(model) for disjunct in self.disjuncts)def formula(self):if len(self.disjuncts) == 1:return self.disjuncts[0].formula()return " ∨  ".join([Sentence.parenthesize(disjunct.formula())for disjunct in self.disjuncts])def symbols(self):return set.union(*[disjunct.symbols() for disjunct in self.disjuncts])# 定义 -> (推出)的类
class Implication(Sentence):def __init__(self, antecedent, consequent):Sentence.validate(antecedent)Sentence.validate(consequent)self.antecedent = antecedentself.consequent = consequentdef __eq__(self, other):return (isinstance(other, Implication)and self.antecedent == other.antecedentand self.consequent == other.consequent)def __hash__(self):return hash(("implies", hash(self.antecedent), hash(self.consequent)))def __repr__(self):return f"Implication({self.antecedent}, {self.consequent})"def evaluate(self, model):return ((not self.antecedent.evaluate(model))or self.consequent.evaluate(model))def formula(self):antecedent = Sentence.parenthesize(self.antecedent.formula())consequent = Sentence.parenthesize(self.consequent.formula())return f"{antecedent} => {consequent}"def symbols(self):return set.union(self.antecedent.symbols(), self.consequent.symbols())# 分治判断
class Biconditional(Sentence):def __init__(self, left, right):Sentence.validate(left)Sentence.validate(right)self.left = leftself.right = rightdef __eq__(self, other):return (isinstance(other, Biconditional)and self.left == other.leftand self.right == other.right)def __hash__(self):return hash(("biconditional", hash(self.left), hash(self.right)))def __repr__(self):return f"Biconditional({self.left}, {self.right})"# 我理解的重点:# 就是 判断一个东西的正确性 可以从两个方面来判断"""1.从正面判断它是正确的2.从它的反面判断是错的, 即判断正面是正确的"""def evaluate(self, model):return ((self.left.evaluate(model)and self.right.evaluate(model))or (not self.left.evaluate(model)and not self.right.evaluate(model)))def formula(self):left = Sentence.parenthesize(str(self.left))right = Sentence.parenthesize(str(self.right))return f"{left} <=> {right}"def symbols(self):return set.union(self.left.symbols(), self.right.symbols())def model_check(knowledge, query):"""Checks if knowledge base entails query."""def check_all(knowledge, query, symbols, model):"""Checks if knowledge base entails query, given a particular model."""# If model has an assignment for each symbolif not symbols:# If knowledge base is true in model, then query must also be trueif knowledge.evaluate(model):return query.evaluate(model) # 返回query的真假情况return True # CS50_1 的视频中, 老师说: 我们并不关心query的真假, 我们只关心根据这个真的库推出的 query的真假, 好像还是有点玄 ? # 相当于处于一个 可正可错的薛定谔的猫 ? 我们证明不了它是错的, 那么它就是对的 ? else:# Choose one of the remaining unused symbolsremaining = symbols.copy()p = remaining.pop()# Create a model where the symbol is true# 分治model_true = model.copy()model_true[p] = True# Create a model where the symbol is falsemodel_false = model.copy()model_false[p] = False# Ensure entailment holds in both models"""如何理解 这里的 and可以先看这个文件的第 213 行对于事件 ABC 如果    ✔××  -> True那么    ×✔✔ -> False 如果这两个都成立, 那么即可说明, 对于A为真, BC为假时, 才能得到 "True"的结果"""return (check_all(knowledge, query, remaining, model_true) andcheck_all(knowledge, query, remaining, model_false))# Get all symbols in both knowledge and querysymbols = set.union(knowledge.symbols(), query.symbols())# Check that knowledge entails queryreturn check_all(knowledge, query, symbols, dict())

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

  1. Python使用中文注释和输出中文(原创)

    刚开始学习python,需要在Python中注释中文和输出中文,现在开始尝试: 仅为初步学习参考,高手请绕行. -------------------------------------------- ...

  2. python加中文注释_Python使用中文注释和输出中文(原创)

    刚开始学习python,需要在Python中注释中文和输出中文,现在开始尝试: 仅为初步学习参考,高手请绕行. -------------------------------------------- ...

  3. python输入中文注释时报错

    在写python脚本的时候,当输入的注释为中文的时候会报出这样的错误: ASCII character '\xe4' in file getoptTest.py on line 14, but no  ...

  4. python 入门学习---模块导入三种方式及中文注释

    Python 有三种模块导入函数 1. 使用import 导入模块 import modname : 模块是指一个可以交互使用,或者从另一Python 程序访问的代码段.只要导入了一个模块,就可以引用 ...

  5. python 中文注释

    python 默认中文注释会报错,解决方案如下 python 中文注释 # encoding=utf-8print('hello python') # 这是第一个程序

  6. python语言中文社区-python解决中文

    广告关闭 腾讯云双11爆品提前享,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高满返5000元! python 添加中文注释时出现运行失败. 需要在顶部设置编码. # coding ...

  7. 为什么python注释不能中文_python中输入中文注释是无法编译

    在python程序编写时,有时候我们会用中文对程序段进行相应的注释,以增加程序的可读性,但是有时候加了中文注释后,编译时会出现编码无法编译的报错,这是由于编码格式设置不正确的原因. 工具/原料 程序语 ...

  8. Python 中文注释报错解决方法

    Python 中文注释报错解决方法 参考文章: (1)Python 中文注释报错解决方法 (2)https://www.cnblogs.com/cjiong/p/5881983.html 备忘一下.

  9. python中单行注释_Python中的单行、多行、中文注释方法

    Python中的单行.多行.中文注释方法 一.python单行注释符号(#) python中单行注释采用 #开头 示例:#this is a comment 二.批量.多行注释符号 多行注释是用三引号 ...

最新文章

  1. 巧妙解法:买卖股票最佳时机
  2. library的英语怎么读音_library怎么读声音
  3. python怎么查看网页编码格式_怎么用python爬取网页文字?
  4. python替代hadoop_Python连接Hadoop数据中遇到的各种坑(汇总)
  5. Java知识系统回顾整理01基础03变量03字面值
  6. 8种图数据库对 NULL 属性值支持情况
  7. [HDU] 1533 Going Home
  8. 谷歌浏览器设置信任_Win10系统下谷歌浏览器怎么添加信任网址/站点
  9. 万能账号密码使用详解,黑客常用的入门级操作
  10. java裂变_微信现金红包单一红包、裂变红包(Java版)
  11. photoshop怎么设计淘宝天猫海报amp;nb…
  12. 求两个矢量的夹角(带正负)
  13. 【数值优化之凸集与凸函数】
  14. 搭建IIS文件服务器
  15. 【EasyRL学习笔记】第七章 深度Q网络进阶技巧(Double-DQN、Dueling-DQN、Noisy-DQN、Distributional-DQN、Rainbow-DQN)
  16. Java 读取resources下的文件
  17. 怎样启动python_如何运行python
  18. 测绘技术设计规定最新版_测绘标准及规范(附带下载)
  19. BVS智能视频分析—智慧城管解决方案
  20. 无法读取此系统上以前注册的服务器的列表。请在“已注册的服务器”窗口中重新注册您的服务器

热门文章

  1. 个人秋招面经——蚂蚁支付宝体验技术部
  2. linux edac服务,使用edac工具来检测服务器内存故障.
  3. 顶级开发师教你用Python做一个哄女友神器,小白可上手
  4. php把中文字符串拆分为单个字,php中UTF8字符串进行单字分割返回数组(包含中文)...
  5. javascript 弹窗与控制台日志
  6. 2022年Android Studio详细下载,安装使用教程
  7. Android Studio内存大小配置及显示
  8. 软件设计原则-开闭原则
  9. VPP三层网络互联配置
  10. 抖音seo排名 抖音搜索关键词如何布局?