def __init__(self, file_name): self.file_name = file_name self.Scales = Variable() self.Path = Variable() self.Cost = Variable() self.assertz = Functor("assertz", 1) self.retract = Functor("retract", 1) self.vuelos = Functor("vuelos", 5) self.edge = Functor("edge", 3) self.prolog = Prolog() self.prolog.consult(self.file_name)
def test_issue_3(self): """ Problem with variables in lists https://code.google.com/p/pyswip/issues/detail?id=3 """ from pyswip import Prolog, Functor, Variable, Atom from deepstr import deep_str p = Prolog() f = Functor('f', 1) A = Variable() B = Variable() C = Variable() x = f([A, B, C]) x = Functor.fromTerm(x) args = x.args[0] self.assertFalse(args[0] == args[1], "Var A equals var B") self.assertFalse(args[0] == args[2], "Var A equals var C") self.assertFalse(args[1] == args[2], "Var B equals var C") self.assertFalse(A == B, "Var A equals var B") self.assertFalse(B == C, "Var A equals var C") self.assertFalse(A == C, "Var B equals var C") # A more complex test x = f([A, B, 'c']) x = Functor.fromTerm(x) args = x.args[0] self.assertEqual(type(args[0]), Variable) self.assertEqual(type(args[1]), Variable) self.assertEqual(type(args[2]), Atom) # A test with repeated variables x = f([A, B, A]) x = Functor.fromTerm(x) args = x.args[0] self.assertEqual(type(args[0]), Variable) self.assertEqual(type(args[1]), Variable) self.assertEqual(type(args[2]), Variable) self.assertTrue( args[0] == args[2], "The first and last var of " "f([A, B, A]) should be the same")
def test_issue_3(self): """ Problem with variables in lists https://code.google.com/p/pyswip/issues/detail?id=3 """ from pyswip import Prolog, Functor, Variable, Atom from deepstr import deep_str p = Prolog() f = Functor('f', 1) A = Variable() B = Variable() C = Variable() x = f([A, B, C]) x = Functor.fromTerm(x) args = x.args[0] self.assertFalse(args[0] == args[1], "Var A equals var B") self.assertFalse(args[0] == args[2], "Var A equals var C") self.assertFalse(args[1] == args[2], "Var B equals var C") self.assertFalse(A == B, "Var A equals var B") self.assertFalse(B == C, "Var A equals var C") self.assertFalse(A == C, "Var B equals var C") # A more complex test x = f([A, B, 'c']) x = Functor.fromTerm(x) args = x.args[0] self.assertEqual(type(args[0]), Variable) self.assertEqual(type(args[1]), Variable) self.assertEqual(type(args[2]), Atom) # A test with repeated variables x = f([A, B, A]) x = Functor.fromTerm(x) args = x.args[0] self.assertEqual(type(args[0]), Variable) self.assertEqual(type(args[1]), Variable) self.assertEqual(type(args[2]), Variable) self.assertTrue(args[0] == args[2], "The first and last var of " "f([A, B, A]) should be the same")
def Query(self, parametro): lista = [] parametro = Functor(parametro) query = Query(parametro(self.X)) while query.nextSolution(): lista.append(str(self.X.get_value())) query.closeQuery() return lista
def parse_ins(instruction) -> list and list and list: if instruction[-1] != ';': instruction += ';' terms = [] # if need var(s) vars = [] statements = [] # if need True or False pnames = re.compile( r'\[.+\]|[\w\d]+') # find names(vars|lists|strings|ints) in atoms plist = re.compile(r'\[.+\]') # find list # find predirects for pred, atoms in re.findall(r'([^\(\)\,\s]+|\S)(\([^\)]+\))\;', instruction): names = pnames.findall(atoms) items = [] there_is_var = False for atom in names: atom = atom.strip() if atom[0].isupper(): # check for var any_var = Variable() # link to Prologs var items.append(any_var) vars.append((atom, any_var)) there_is_var = True elif atom.isdigit(): # check for int items.append(int(atom)) elif plist.search(atom): # check for list items.append(literal_eval(atom)) else: try: # check for float items.append(float(atom)) except ValueError: items.append(atom) if there_is_var: terms.append(Functor(pred, len(names))(*items)) else: statements.append((Functor(pred, len(names))(*items), pred + atoms)) return terms, vars, statements
def main(): letters = "S E N D M O R Y".split() prolog = Prolog() sendmore = Functor("sendmore") prolog.consult("money.pl") X = Variable() call(sendmore(X)) r = X.value for i, letter in enumerate(letters): print(letter, "=", r[i]) print("That's all...")
def main(): prolog = Prolog() prolog.consult("Parientes.pl") result = [] progenitor = Functor("progenitor", 2) X = Variable() q = Query(progenitor("pedro", X)) while q.nextSolution(): print(X.value) result.append(X.value) q.closeQuery() return result
def check_prolog_knowledge_base(): global answers consult = Functor("consult", 1) call(consult(file_path)) prolog = Prolog() arr = list( prolog.query( "run({}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, X)". format(*answers))) if len(arr) > 0: v = arr[0]['X'] return True, v else: v = "Такого героя нет. Добавьте его." return False, v
def main(): prolog = Prolog() prolog.consult("coins.pl") count = int(raw_input("How many coins (default: 100)? ") or 100) total = int(raw_input("What should be the total (default: 500)? ") or 500) coins = Functor("coins", 3) S = Variable() q = Query(coins(S, count, total)) i = 0 while q.nextSolution(): ## [1,5,10,50,100] s = zip(S.value, [1, 5, 10, 50, 100]) print i, for c, v in s: print "%dx%d" % (c, v), print i += 1 q.closeQuery()
def main(): prolog = Prolog() prolog.consult("kanankiri.pl") count = int(input("Berapa jumlahnya kiri? ") or 100) total = int(input("Berapa total semuanya? ") or 500) kanankiri = Functor("kanankiri", 3) S = Variable() q = Query(kanankiri(S, count, total)) i = 0 while q.nextSolution(): ## [1,5,10,50,100] s = zip(S.value, [1, 5, 10, 50, 100]) print(i), for c, v in s: print("%dx%d" % (c, v)), print() i += 1 q.closeQuery()
def draw_card(self): '''Pesca una carta dal mazzo di carte, setta l'attributo prima contenente la carta pescata e la aggiunge alle carte uscite''' # pesca una carta dal mazzo mazzostr = '[' if len(self.mazzo) > 0: for card in self.mazzo: mazzostr += str(card) + ',' mazzostr = mazzostr[:-1] + ']' else: mazzostr += ']' result = self.query('draw_card(' + mazzostr + ', Prima, Resto)') for r in result: prima = r['Prima'] self.mazzo = r['Resto'] prima = prima.replace('card(', '').replace(' ', '').replace(')', '').split(',') self.prima = Functor('card', 2, prima) self.uscite.append(self.prima)
def consult(values): prolog = Prolog() # Call class prolog.consult("coins.pl") # Call consult count = int(values[0] or 100) total = int(values[1] or 500) coins = Functor("coins", 3) S = Variable() q = Query(coins(S, count, total)) i = 0 # Consult the kdb while q.nextSolution(): ## [1,5,10,50,100] s = zip(S.value, [1, 5, 10, 50, 100]) print(i, end=" ") for c, v in s: print("%dx%d" % (c, v), end=" ") print() i += 1 q.closeQuery()
def Pick(self, occupation: str, age: int, prev_accidents: int, car_model: int) -> Set[Tuple[int, str, str, int, float, str]]: INSURANCE_ID, INSURANCE_TYPE, INSURANCE_COVERAGE, \ INSURANCE_DURATION, INSURANCE_PRICE, INSURANCE_PRICE_RANGE = \ Variable(), Variable(), Variable(), Variable(), Variable(), Variable() fpick = Functor("pick", 10) query = Query( fpick(occupation, age, prev_accidents, car_model, INSURANCE_ID, INSURANCE_TYPE, INSURANCE_COVERAGE, INSURANCE_DURATION, INSURANCE_PRICE, INSURANCE_PRICE_RANGE)) results = set() while query.nextSolution(): results.add( (INSURANCE_ID.value, str(INSURANCE_TYPE.value), str(INSURANCE_COVERAGE.value), INSURANCE_DURATION.value, INSURANCE_PRICE.value, str(INSURANCE_PRICE_RANGE.value))) query.closeQuery() return results
while criterion.startswith("(f") or criterion.startswith("f"): sliceLab.append(criterion.split(",",1)[0][criterion.find("f"):]) criterion = criterion.split(",",1)[1] criterion = criterion[1:-2] # sliceVar = [] sliceVar = criterion.split(",") i = 0 while i<len(sliceVar): sliceVar[i] = sliceVar[i].replace("(", "_").replace(")","") i = i+1 # sliceVar = str(sliceVar).replace("(", "_").replace(")","") # print(sliceVar) prolog.consult(file) defF = Functor("defF",2) refF = Functor("refF",2) flow = Functor("flow",2) control = Functor("control",2) dataDepF = Functor("dataDepF",3) varStack = [] loopStack = {} iteStack = {} switchStack = {} callMStack = {} #the location where callMethod ,its next lab jumpStack = {} #jumpStack[lab] = jumpToLab controlStack = {} callCount={} startTime =time.time()
def consultaProlog(pregunta): relacion = '0' nombre1 = '0' nombre2 = '0' unica = 0 prolog = Prolog() prolog.consult("Parientes.pl") result = [] value = '' # Solicito la entrada #print('Ingrese la pregunta:') #pregunta = input() y = pregunta.split(' ') p = 0 while p != len(y): if relacion == '0': relacion, unica = relaciones(y[p]) if nombre1 == '0': nombre1 = nombres(y[p]) elif nombre2 == '0' and nombre1 != '0': nombre2 = nombres(y[p]) p = p + 1 if relacion != '0' and nombre1 != '0' and nombre2 != '0': if bool( list( prolog.query("" + relacion + "(" + nombre1 + "," + nombre2 + ")"))): value = 'Asi es!' #print("Asi es!") return value else: value = 'Incorrecto!' #print('Incorrecto!') return value elif relacion != 0 and nombre1 != '0' and nombre2 == '0' and unica != 1: rel = Functor("" + relacion + "", 2) X = Variable() q = Query(rel("" + nombre1 + "", X)) print('') print('') while q.nextSolution(): value = value + ', ' + str(X.value) #print("LA RESPUESTA ES: ", X.value) q.closeQuery() return value elif relacion != '0' and nombre1 != '0' and nombre2 == '0' and unica == 1: if bool(list(prolog.query("" + relacion + "(" + nombre1 + ")"))): value = 'Asi es!' #print("Asi es!") return value else: value = 'Incorrecto!' return value #print("Incorrecto!") elif relacion == '0' and nombre1 == '0' and nombre2 == '0': value = 'Perdon, no logro entenderte!!' return value
from pyswip import Functor, Variable, Query, call assertz = Functor("assertz", 1) father = Functor("father", 2) call(assertz(father("mi", "j"))) call(assertz(father("mi", "g"))) X = Variable() q = Query(father("mi", X)) while q.nextSolution(): print "Hello,", X.value q.closeQuery()
def consultaProlog(pregunta): relacion = '0' nombre1 = '0' nombre2 = '0' unica = 0 result = [] value = '' #Instancia de la clase prolog prolog = Prolog() #Definicion del erchivo que se consultara prolog.consult("Ejercicio1.pl") y = pregunta.split(' ') p = 0 while p != len(y): #si no hay ninguna relacion en la variable relacion, busco dentro de los diccionarios if relacion == '0': relacion, unica = relaciones(y[p]) #Verifico que existan los nombres dentro del diccionario if nombre1 == '0': nombre1 = nombres(y[p]) elif nombre2 == '0' and nombre1 != '0': nombre2 = nombres(y[p]) p = p + 1 #Verifica si es consulta de tipo hecho if relacion != '0' and nombre1 != '0' and nombre2 != '0': #Consulta por medio de prolog.query(la consulta) y esta devuelve true o false if bool( list( prolog.query("" + relacion + "(" + nombre1 + "," + nombre2 + ")"))): value = 'Asi es!' return value else: value = 'Incorrecto!' return value #Verifica si es consulta de tipo variable incognita elif relacion != 0 and nombre1 != '0' and nombre2 == '0' and unica != 1: #Se define la estrucutura arbitraria functor rel = Functor("" + relacion + "", 2) #Variable incognita X X = Variable() #Consulta q = Query(rel("" + nombre1 + "", X)) while q.nextSolution(): value = value + ', ' + str(X.value) q.closeQuery() return value #Verifica si es consulta de tipo unica elif relacion != '0' and nombre1 != '0' and nombre2 == '0' and unica == 1: if bool(list(prolog.query("" + relacion + "(" + nombre1 + ")"))): value = 'Asi es!' return value else: value = 'Incorrecto!' return value #Si no existe ninguna palabra dentro de los diccionarios, no entiende la sentencia el sistema elif relacion == '0' and nombre1 == '0' and nombre2 == '0': value = 'Perdon, no logro entenderte!!' return value