I'm looking for the algorithm of backward and forward chaining to implement it with Python. I looked on the internet, but I didn't find too much. I looked in Wikipedia too but I just found some rules and I didn't find the algorithms.
-
thanx for help @GuyCoder – Adelov Mar 26 '17 at 12:57
3 Answers
I know you originally tagged your earlier question with Python so I will limit this to just Python.
When looking for code examples one good place to look is in the Github repositories. Querying for backward chaining
and then limiting the results to Python
will yield this query You can do the same for forward chaining
.
Note that you will have to find the code samples you like and then thoroughly test it before making using of it. There are great examples there, but more likely attempts at it that are incorrect. Plan to spend a few days with them and create lots of test cases. All of the code there comes with no guarantees.
If you want just the algorithm then find books for Artificial Intelligence
such as Artificial Intelligence ... by George F Luger or Artificial Intelligence ... by Russell and Norvig.

- 30,230
- 67
- 195
- 328

- 24,501
- 8
- 71
- 136
Forward-chaining inference engines can be implemented relatively easily in Python. This is a list of inference rules:
mammal(A) ==> vertebrate(A).
vertebrate(A) ==> animal(A).
vertebrate(A),flying(A) ==> bird(A).
vertebrate("duck").
flying("duck").
mammal("cat").
These rules can be translated into Python:
global facts
global is_changed
is_changed = True
facts = [["vertebrate","duck"],["flying","duck"],["mammal","cat"]]
def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True
while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "mammal":
assert_fact(["vertebrate",A1[1]])
if A1[0] == "vertebrate":
assert_fact(["animal",A1[1]])
if A1[0] == "vertebrate" and ["flying",A1[1]] in facts:
assert_fact(["bird",A1[1]])
print(facts)
From the initial set of facts, the inference engine generates this list:
[['vertebrate', 'duck'], ['flying', 'duck'], ['mammal', 'cat'], ['animal', 'duck'], ['bird', 'duck'], ['vertebrate', 'cat'], ['animal', 'cat']]

- 30,230
- 67
- 195
- 328
global facts
global is_changed
is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]
def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True
while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "seed":
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
if A1[0] == "plant" and ["eating",A1[1]] in facts:
assert_fact(["human",A1[1]])
print(facts)
-
2Welcome to Stack Overflow! Code-only answers are not particularly helpful. Please include a brief description of how this code solves the problem. – 4b0 Mar 02 '20 at 10:57