def gather_inside_outside_quote_facts(R, doc): inside = False R['insideq'] = Relation('insideq') R['outsideq'] = Relation('outsideq') for token in doc: if token.text == '"': inside = not inside else: if inside: fact(R['insideq'], token.i) else: fact(R['outsideq'], token.i)
def star_wars_logic(): x = var() parent = Relation() facts(parent, ("Darth Vader", "Luke Skywalker"), ("Darth Vader", "Leia Organa"), ("Han Solo", "Kylo Ren"), ("Leia Organa", "Kylo Ren")) print(run(0, x, parent(x, "Luke Skywalker"))) print(run(0, x, parent("Darth Vader", x))) grandparent = Relation() facts(grandparent, ("Darth Vader", "Kylo Ren")) print(run(1, x, grandparent(x, "Kylo Ren")))
def I(): parent = Relation() facts(parent, ("Darth Vader", "Luke Skywalker"), ("Darth Vader", "Leia Organa"), ("Leia Organa", "Kylo Ren"), ("Han Solo", "Kylo Ren")) x = var() print(run(1, x, parent(x, "Luke Skywalker"))) y = var() print(run(2, y, parent("Darth Vader", y))) grand_parents = Relation() facts(grand_parents, ("Darth Vader", "Kylo Ren")) z = var() print(run(1, z, grand_parents(z, "Kylo Ren")))
def logicBased(): x = var() print(run(1, x, eq(x, 5))) z = var() print(run(1, x, eq(x, z), eq(z, 3))) print(run(1, x, eq((1, 2), (1, x)))) print(run(2, x, membero(x, (1, 2, 3)), membero(x, (2, 3, 4)))) z = var('test') print(z) a, b, c = vars(3) print(a) print(b) print(c) parent = Relation() facts(parent, ("Homer", "Bart"), ("Homer", "Lias"), ("Abe", "Homer")) print(run(2, x, parent("Homer", x))) y = var() print(run(1, x, parent(x, y), parent(y, 'Bart'))) def grandparent(x, z): y = var() return conde((parent(x, y), parent(y, z))) print(run(1, x, grandparent(x, 'Bart'))) menu() #calls the menu function (a menu loop)
def main(): parent = Relation() facts(parent, ("Darth Vader", "Luke Skywalker"), ("Darth Vader", "Leia Organa"), ("Leia Organa", "Kylo Ren"), ("Han Solo", "Kylo Ren")) # Darth Vader is Luke and Leia's Parent # Leia and Han are Kylo's Parents run(1, x, parent(x, "Luke Skywalker")) # What is x, such that x is the parent of Luke run(2, y, parent("Darth Vader", y)) # What is y, such that y is the children of Vader grandparent = Relation() facts(grandparent, ("Darth Vader", "Kylo Ren")) # Darth Vader is Kylo Ren's Grandparent run(1, z, grandparent(z, "Kylo Ren")) # What is z, such that z is the grandparent of Kylo Ren #OR y = var() run(1, x, parent(x, y), parent(y, "Kylo Ren"))
def start(self): self.parent = Relation() x = var() facts(self.parent, ("DarthVader", "LukeSkywalker"), ("DarthVader", "LeiaOrgana"), ("LeiaOrgana", "KyloRen"), ("HanSolo", "KyloRen") ) lukesParent = run(1, x, self.parent(x, "LukeSkywalker")) darthsChildren =run(2, x, self.parent("DarthVader", x)) print("Luke Skywalkers parent is: ", lukesParent) print("Darth Vaders children are: ", darthsChildren) kylosGrandparent = run(1, x,self.grandparent(x, "KyloRen")) print("Kylo Ren's grand parent is: ", kylosGrandparent) self.familyTreeDataStructures()
def gather_facts(doc): R = {'LEMMA': Relation('LEMMA'), 'root': Relation('root'), 'head': Relation('head')} for rel in DEPS: R[rel] = Relation(rel) for tok in doc: facts(R['LEMMA'], (tok.i, tok.lemma_)) if not tok.pos_ in R: R[tok.pos_] = Relation(tok.pos_) fact(R[tok.pos_], (tok.i)) facts(R[tok.dep_ if tok.head.i != tok.i else 'root'], (tok.head.i if tok.head.i != tok.i else -1, tok.i)) facts(R['head'], (tok.head.i if tok.head.i != tok.i else -1, tok.i)) if not tok.ent_type_ in R: R[tok.ent_type_] = Relation(tok.ent_type_) fact(R[tok.ent_type_], (tok.i)) gather_inside_outside_quote_facts(R, doc) return R
from kanren import run, eq, membero, var, conde, vars, Relation, facts price = Relation() userRatings = Relation() screenSize = Relation() pixelDensity = Relation() numOfCores = Relation() weight = Relation() print("Apple Iphone 11 Pro VS Samsung Galaxy S20 Ultra") print() facts(price, ('1000', 'Iphone 11'), ('1200', 'S20')) facts(userRatings, ('4.7', 'Iphone 11'), ('4.6', 'S20')) facts(screenSize, ('5.8 inches', 'Iphone 11'), ('6.9 inches', 'S20')) facts(pixelDensity, ('358 PPI', 'Iphone 11'), ('511 PPI', 'S20')) facts(numOfCores, ('6 Core', 'Iphone 11'), ('8 Core', 'S20')) print("If answer Iphone then enter 1, if S20 then enter 2") answer = input("Which do you think has a better price? ") applePrice = (run(1, x, price(x, "Iphone 11")))[0] samsungPrice = (run(1, x, price(x, "S20")))[0] if answer == "1": print("You are right! The Iphone only costs $", applePrice) elif answer == "2": print("You are wrong! The Samsung costs $", samsungPrice, " which is more than ", (int(samsungPrice) - int(applePrice)), " dollars") else: print("Wrong input!")
# Two expressions to match pattern = (mul, (add, 1, x), y) # (1 + x) * y expr = (mul, 2, (add, 3, 1)) # 2 * (3 + 1) print(run(0, (x, y), eq(pattern, expr))) # prints ((3, 2),) meaning # x matches to 3 # y matches to 2 pattern = (add, (mul, 2, r), s) # (2 * r) + s expr = (add, 5, (mul, 6, 2)) # 5 + (6 * 2) print(run(0, (r, s), eq(pattern, expr))) # prints ((6, 5),) meaning # r matches to 6 # s matches to 5 results() pizza() pizza = Relation() pizza2 = Relation() facts(pizza, ('Pepperoni', 'Sausage'), ('Pepperoni', 'Bacon'), ('Ham', 'Pepperoni')) facts(pizza2, ('Pineapple', 'Ham'), ('Pineapple', 'Sardines'), ('Anchovies', 'Pineapple')) print(run(1, x, pizza(x, 'Sausage'))) print(run(2, x, pizza('Pepperoni', x))) print(run(3, x, pizza2(x, 'Ham'))) print(run(4, x, pizza2('Pineapple', x))) def mypizza(x, z): y = var() return conde((pizza(x, y), pizza(y, z)))
#function to convert .docx to .txt file def convert_doc_to_text(str): MY_TEXT = docx2txt.process(str) #function call to process .docx file fileName = str.split('.')[0] #obtains file name #creates a .txt file with the file name with open(fileName + '.txt', "w") as text_file: print(MY_TEXT, file=text_file) #prints the information into the text file #declared variables synonym = Relation() #create a relation variable to identify synonym words no_synonym = Relation( ) #create a variable to identify if no synonyms are stored in the word bank x = var() #holds the value of run() y = var() #holds the value of run() # Threshold levels (small, medium, high) s_threshold = 10 m_threshold = 18 h_threshold = 25 #opens the .txt file in order to obtain the synonym words with open('synonyms.txt') as file: synlist = [ line.strip().split(',') for line in file if line and line[0].isalpha() ]
from kanren import run, eq, membero, vars, conde, Relation, facts, var #Austin Bradstreet, 004880497 #CS-351, 1st attempt at using Python care = 'Austin' shel = 'Valley of Animal Friends' caretaker = Relation() shelter = Relation() facts(shelter, (shel, care)) animal_name = Relation() def contains(s, animal): return conde((shelter(s, care), caretaker(care, animal))) print('\nAnimal Shelter menu') print('______________________') print('1: Animal Shelter Name') print('2: Caretaker Name') print('3: Animals in shelter') print('4: Add animals') print('5: Add name to animal') print('6: exit') print('_______________________\n')
from kanren import run, var from kanren import Relation, facts I = var() # Ingrediente P = var() # Plato T = var() # Tipo de plato M = var() # Malestar es_ingred_de = Relation() facts(es_ingred_de, ("tomate", "ensalada"), ("limon", "ensalada"), ("pollo", "aguadito"), ("arvejas", "aguadito"), ("zapallo", "picante"), ("cebolla", "picante"), ("maracuya", "helado"), ("saborizante", "helado"), ("aguardiente", "calientito"), ("te", "calientito")) ##TIPO DE ALIMENTOS es_un_tipoalimento_de = Relation() facts(es_un_tipoalimento_de, ("ensalada", "entrada"), ("aguadito", "sopa"), ("picante", "platofondo"), ("helado", "postre"), ("calientito", "bebida")) ##RECOMENDADO PARA bueno_contra = Relation() facts(bueno_contra, ("tomate", "caries"), ("limon", "gripe"), ("cebolla", "gripe"), ("zanahoria", "ceguera"), ("te", "stress"), ("maracuya", "stress")) ##EXCESO #en_exceso_provoca(huevo, colesterol) #en_exceso_provoca(platano, diabetes) #en_exceso_provoca(carne, artritis) #en_exceso_provoca(aceite, colesterol)
# -*- coding: utf-8 -*- from kanren import facts, Relation, run, var, conde, lall, lany, eq from kanren.core import success edges = Relation() right = Relation() down = Relation() left = Relation() facts(edges, (1, 'U', 1), (2, 'U', 2), (3, 'U', 3), (4, 'U', 1), (5, 'U', 2), (6, 'U', 3), (7, 'U', 4), (8, 'U', 5), (9, 'U', 6), (1, 'D', 4), (2, 'D', 5), (3, 'D', 6), (4, 'D', 7), (5, 'D', 8), (6, 'D', 9), (7, 'D', 7), (8, 'D', 8), (9, 'D', 9), (1, 'R', 2), (2, 'R', 3), (3, 'R', 3), (4, 'R', 5), (5, 'R', 6), (6, 'R', 6), (7, 'R', 8), (8, 'R', 9), (9, 'R', 9), (1, 'L', 1), (2, 'L', 1), (3, 'L', 2), (4, 'L', 4), (5, 'L', 4), (6, 'L', 5), (7, 'L', 7), (8, 'L', 7), (9, 'L', 8)) # def walk(pos, path, end_pos): # x = var() # lany(lall(eq(path, []), eq(pos, end_pos)), # lall( # edges(pos, path[0], x), # walk(x, path[1:], end_pos))) def walk(pos, path, end_pos): if eq(path, []): eq(pos, end_pos) return success
from kanren import Relation, lany woman = Relation() man = Relation() year_of_birth = Relation() def human(a_person): return lany( woman(a_person), man(a_person), )
# -*- coding: utf-8 -*- """ Created on Tue Apr 4 09:06:23 2021 @author: Hp """ from kanren import run,var x = var() y = var() z = var() from kanren import Relation,facts,conde parent = Relation() facts(parent, ('isidro','daniel'), ('isidro','hilda'), ('ana','daniel'), ('ana','hilda'), ('elena','betza'), ('elena','severo'), ('elena','julia'), ('daniel','tahere'), ('daniel','didar'), ('betza','tahere'), ('betza','didar'), ('severo','elisa'), ('jazmin','elisa'), ('julia','marifer'), ('julia','jose'),
# -*- coding: utf-8 -*- """ Created on Mon Apr 5 11:31:49 2021 @author: IBM GAMER """ from kanren import run, eq, var x = var() y = var() z = var() from kanren import Relation, facts, conde, lall, lany padre = Relation() facts(padre, ('francisco', 'pablo'), ('francisco', 'rene'), ('francisco', 'rosa'), ('francisco', 'barbara'), ('manuela', 'pablo'), ('manuela', 'rene'), ('manuela', 'rosa'), ('manuela', 'barbara'), ('felipe', 'elias'), ('felipe', 'ramiro'), ('felipe', 'fabiana'), ('felipe', 'lucy'), ('tomasa', 'elias'), ('tomasa', 'ramiro'), ('tomasa', 'fabiana'), ('tomasa', 'lucy'), ('rene', 'freddy'), ('rene', 'adriana'), ('fernanda', 'freddy'), ('fernanda', 'adriana'), ('juan', 'yolanda'), ('juan', 'yolanda'), ('rosa', 'rosmery'), ('rosa', 'rosmery'), ('elias', 'nayra'), ('elias', 'maria'), ('elias', 'gabi'), ('elias', 'gabriel'), ('barbara', 'nayra'), ('barbara', 'maria'), ('barbara', 'gabi'), ('barbara', 'gabriel'), ('ramiro', 'rocio'), ('ramiro', 'miguel'), ('alejandra', 'rocio'), ('alejandra', 'miguel')) print(run(4, x, padre("gabriel", x))) #print(run(4,x, padre("gabriel",y,x)) ) #print(run(2,x, padre("rosa",x,x)))
if (nb == 0): print (" You have not any " + listing) return (0) else: return (1) def show(y, listing): for v in y: result.append(v) for i in range(len(result)): result[i] print (" You have " + str(i + 1) + " " + listing + " :") for i in range(len(result)): print ("==> " + result[i]) employee = Relation() Trainee = Relation() traineenb = 0 managernb = 0 managednb = 0 username = input(" Hello, I'am doing the listing of the employees and they're managers\n What is your name ?\n") print(" Welcome " + username + "!\n") Employees = input(" You have to add your manager, the people you are managing and your trainee if you have one\n Enter the keyword you need to enter ?\n Manager, Managed, Trainee\n") while (1): if (Employees == "Trainee" or Employees == "trainee"): trainee = input(" Enter the name of your trainee\n") facts(Trainee, (username, trainee))
def __init__(self): self.parent= Relation()
from kanren import run, var from kanren import Relation, facts M = var() P = var() H = var() es_esposo_de = Relation() facts(es_esposo_de, ("Sabino", "Rosalia"), ("David", "Flor"), ("Rene", "Nelith")) es_padre_de = Relation() facts(es_padre_de, ("Sabino", "David"), ("Sabino", "Rene"), ("Sabino", "Hernan"), ("David", "Angie"), ("Rene", "Marcelo")) print("Para todo hijo hay mamá") print(run(10, (H, M), es_padre_de(P, H), es_esposo_de(P, M))) print("inferencia dado un hijo determina quién es la mamá") H1 = "Marcelo" print(run(10, M, es_padre_de(P, H1), es_esposo_de(P, M)))
#Emanuel Ordonez #Assignment 2 #CS 351 import kanren from kanren import run, var, conde, Relation, facts cor = 'CS 351' prof = 'Cary Jardin' #assigning professor to a course course = Relation() facts(course, (cor, prof)) #assigning professor to all students professor = Relation() #value to help use run def studies(c, student): return conde((course(c, prof), professor(prof, student))) #Menu for app print('\n\nCourse Menu') print('_____________________________') print('1: Course Name') print('2: Professor Name') print('3: Add a student') print('4: Students in course') print('5: Quit')
""" An example showing how to use facts and relations to store data and query data This example builds a small database of the US states. The `adjacency` relation expresses which states border each other. The `coastal` relation expresses which states border the ocean. """ from kanren import Relation, fact, run, var adjacent = Relation() coastal = Relation() coastal_states = ( "WA,OR,CA,TX,LA,MS,AL,GA,FL,SC,NC,VA,MD,DE,NJ,NY,CT,RI,MA,ME,NH,AK,HI". split(",")) # ['NY', 'NJ', 'CT', ...] for state in coastal_states: # E.g. 'NY' is coastal fact(coastal, state) # Lines like 'CA,OR,NV,AZ' with open("examples/data/adjacent-states.txt") as f: adjlist = [ line.strip().split(",") for line in f if line and line[0].isalpha() ] # ['CA', 'OR', 'NV', 'AZ'] for L in adjlist: # 'CA', ['OR', 'NV', 'AZ']
""" Name: Kangnan Dong Date: 3/8/2020 Assignment2 Goal: use kanren package to build a family tree """ import json from kanren import Relation, facts, run, conde, var, eq with open('relationships.json') as f: d = json.loads(f.read()) father = Relation() mother = Relation() for item in d['father']: facts(mother, (list(item.keys())[0], list(item.values())[0])) for item in d['mother']: facts(father, (list(item.keys())[0], list(item.values())[0])) def parent(x, y): return conde((father(x, y),), (mother(x,y),)) def grandparent(x, y): temp = var() return conde((parent(x, temp), parent(temp, y))) def sibling(x, y): temp = var() return conde((parent(temp, x), parent(temp, y))) def uncle(x, y): temp = var() return conde((father(temp, x), grandparent(temp, y)))
from kanren import Relation, facts, var, run from Data.PlayerDamageData import * key_enemy = ["KEYENEMY1", "KEYENEMY2", "KEYENEMY3", "KEYENEMY4"] key_dif_multi = ["DIFMULTI1", "DIFMULTI2", "DIFMULTI3", "DIFMULTI4"] enemy_difficult = [0, 0, 0, 0] player_hit_rate = "PLAYERHITRATE" balanceFactor = Relation() difficultyAdjustMax = Relation() difficultyAdjustMin = Relation() damageBalanceFactor = 1.65 #infos retiradas do xml #numero de hits em ordem de tipo de inimigo hits = [0,0,0,0] #numero de usos de ataque em ordem de tipo de inimigo happenings = [0, 0, 0, 0] difficultyMultipliers = [1, 1, 1, 1] itemDistances = [0, 0, 0, 0] #BASEAR EM TEMPO #infos estabelecidas aqui facts(balanceFactor, ("enemy1", "11"), ("enemy2", "10"), ("enemy3", "17"), ("enemy4", "9"))
z = kanren.var() print(run(1, x, eq(x, z), eq(z, 3))) #asks for a number x such that 1,2 equals 1,x print(run(1, x, eq((1, 2), (1, x)))) #uses membero twice to ask for 2 values of x such that x is a member of 1,2,3 and that x is a member of 2,3.4 print(run(2, x, membero(x, (1, 2, 3)), membero(x, (2, 3, 4)))) #creates a logic variable z = kanren.var('test') print(z) #creates multiple logic variables at once a, b, c = var('a'), var('b'), var('c') print(a) print(b) print(c) #creates a parent relationship and uses it to state facts about who is related to who parent = Relation() facts(parent, ("Homer", "Bart"), ("Homer", "Lisa"), ("Abe", "Homer")) print(run(1, x, parent(x, "Bart"))) print(run(2, x, parent("Homer", x))) #uses intermediate variables for complex queries y = var() print(run(1, x, parent(x, y), parent(y, 'Bart'))) #express the grandfather relationship seperatly using conde def grandparent(x, z): y = var() return conde((parent(x, y), parent(y, z))) print(run(1, x, grandparent(x, 'Bart')))
from kanren import var, facts, Relation, run # Declaring a relation, maze_path maze_path = Relation() # Defining a path on a maze # Relation object from Kanren library is used to define different paths # Maze starts at 1, and the finish line is 9 # Path to finish is 1->2->5->6->9 facts(maze_path, (1, 2), (1, 3), (2, 8), (2, 5), (3, 1), (3, 4), (5, 6), (5, 1), (1, 4), (3, 7), (7, 4), (4, 8), (2, 7), (5, 7), (6, 9), (8, 1)) # Function will work its way back from the finish (9) to the start (1) by using the run function # Run function recursively finds the parent of current_position until we reach base case # Once base case is reached, we reverse our string since we traveled from finish to start # String is then printed to user def finish_maze(current_position, path): x = var() if current_position == 1: path = path[::-1] print(path) else: current_position = run(1, x, maze_path(x, current_position))[0] path += ">-%d" % current_position finish_maze(current_position, path) # Function displays start menu for user def start_menu(): print("*** Welcome to the Maze ***")
# -*- coding: utf-8 -*- """ Created on Sat Apr 3 19:20:20 2021 @author: Desktop """ from kanren import run, eq, var #asignar una variable de valor x=var() y=var() #asignacion de valores from kanren import Relation, facts parent = Relation() grandparent=Relation() tios = Relation() primos=Relation() hijos=Relation() #relacion de padre facts(parent, ("miguelina", "amilkar"), ("miguelina", "belen"), ("ernesto", "amilkar"), ("ernesto", "belen"), ("remi","shana"), ("remi","israel"), ("willy", "shana"), ("willly","israel"), ("barbara", "miguelina"), ("barbara", "remi"),
from kanren import vars x = kanren.var() z = kanren.var() y = kanren.var() a, b, c = kanren.vars(3) print(run(1, x, eq(x, 5))) print(run(1, x, eq(x, z), eq(z, 3))) print(run(1, x, eq((1, 2), (1, x)))) print(run(2, x, membero(x, (1, 2, 3)), membero(x, (2, 3, 4)))) print(a, b, c) parent = Relation() facts(parent, ("Homer", "Bart"), ("Homer", "Lisa"), ("Abe", "Homer")) print(run(1, x, parent(x, "Bart"))) print(run(2, x, parent("Homer", x))) print(run(1, x, parent(x, y), parent(y, 'Bart'))) def grandparent(x, z): return conde((parent(x, y), parent(y, z))) print(run(1, x, grandparent(x, 'Bart')))
print the attributes ''' print('\n' + '\t'.join(attributes)) print('=' * 57) ''' for loop prints the prime numbers of all employees ''' for index, i in enumerate(result_id): print(index, data[i - 1]["id"], data[i - 1]["firstName"], data[i - 1]["lastName"], data[i - 1]["jobType"]) ''' Initialize the relations and variables ''' # Initialize the relations: jobType = Relation() x = var() y = var() z = var() ''' store the employee data into the facts to build our relationship and constraints using the Kanren libraries ''' for index, i in enumerate(result_id): facts(jobType, (data[i - 1]["jobType"], data[i - 1]["firstName"], data[i - 1]["lastName"], str(data[i - 1]["id"]))) ''' print the solutions and find out how many jobtype they do correspond for each question ''' findType = ['Engineer', 'Architect', 'Consultant', 'Producer', 'Manager'] for i in findType: '''
from kanren import run, var, fact, Relation x = var() human = Relation() fact(human, "Socrates") def mortal(x): return human(x) sol = run(1, x, mortal(x)) print(sol)