Advertisement
EduPsEudo

Encadeamento pra tras 2

Sep 15th, 2023
891
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.08 KB | None | 0 0
  1. def print_regras(base_conhecimento):
  2.     for i, regra in enumerate(base_conhecimento):
  3.         print(f"Regra {i + 1}: SE", end=" ")
  4.         for condicao in regra["condicao"]:
  5.             print(f"{condicao[0]} = {condicao[1]}", end=" ")
  6.             if condicao != regra["condicao"][-1]:
  7.                 print("E", end=" ")
  8.         print(f"ENTÃO {regra['valor'][0]} = {regra['valor'][1]}")
  9.  
  10. def encad_tras(objetivo, fatos, base_conhecimento):
  11.     n = 0
  12.     for f in fatos:
  13.         for i in base_conhecimento:
  14.             if i["valor"][1] == f[1] and i["valor"][0] == f[0]:
  15.                 for j in i["condicao"]:
  16.                     if j not in fatos:
  17.                         valido = 1
  18.                         for z in fatos:
  19.                             if j[0] == z[0]:
  20.                                 valido = 0
  21.                         if (valido):
  22.                             fatos.append(j)
  23.                             n += 1
  24.  
  25.     return n, fatos
  26.  
  27. def encad_frente(classificatorio, base_conhecimento, atributos, valores):
  28.     fatos = list()
  29.     apli_regras = list()
  30.     temp_atributos = atributos.copy()
  31.     temp_valores = valores.copy()
  32.     temp_base_conhecimento = base_conhecimento.copy()
  33.     flag = 0
  34.     while temp_atributos:
  35.         i = temp_atributos[0]
  36.        
  37.         if i == classificatorio:
  38.             temp_atributos.pop(0)
  39.             temp_valores.pop(0) #!!!!!!
  40.             continue
  41.  
  42.         valores_possiveis = temp_valores[0]
  43.  
  44.         if len(valores_possiveis) == 1:
  45.             resposta = input(f"\nO tipo do/a {i} é {valores_possiveis[0]}? [S/N] ").upper()
  46.             if resposta == "S":
  47.                 fatos.append([i, valores_possiveis[0]])
  48.             elif resposta != "N":
  49.                 print("Digite uma resposta válida!")
  50.  
  51.         else:
  52.             print(f"Qual o tipo do/a {i}? ")
  53.             for f, j in enumerate(valores_possiveis):
  54.                 print(f"[ {f} ] - {j}")
  55.             print("[ -1 ] - Não sei")
  56.             resposta = int(input("Resposta: "))
  57.             if resposta != -1:
  58.                 fatos.append([i, valores_possiveis[resposta]])
  59.  
  60.         temp_atributos.pop(0)
  61.         temp_valores.pop(0)
  62.  
  63.         for k, i in enumerate(temp_base_conhecimento):
  64.             aux = 0
  65.             tam = len(i["condicao"])
  66.             for j in fatos:
  67.                 if j[0] == i["valor"][0] and j[1] != i["valor"][1]:
  68.                     # print(f"Excluir regra valor {i['valor'][0]} = {i['valor'][1]}")
  69.                     # print(i)
  70.                     temp_base_conhecimento.pop(k)
  71.                     break
  72.                        
  73.                    
  74.                 for x in i["condicao"]:
  75.                     if j[0] == x[0] and j[1] == x[1]:
  76.                         tam -= 1
  77.                     elif j[0] == x[0] and j[1] != x[1]:
  78.                         # print(f"exclui regra condição {x[0]} = {x[1]}")
  79.                         # print(i)
  80.                         temp_base_conhecimento.pop(k)
  81.                         if j[0] in temp_atributos:
  82.                             ind = temp_atributos.index(j[0])
  83.                             temp_atributos.pop(ind)
  84.                             temp_valores.pop(ind)
  85.                         aux = 1
  86.                         break
  87.                 if aux == 1:
  88.                     break
  89.    
  90.             if tam == 0:
  91.                 if i not in apli_regras:
  92.                     apli_regras.append(i)
  93.                 if i["valor"][0] == classificatorio:
  94.                     resposta = input(f"\nA partir dos fatos fornecidos {classificatorio} é o/a {i['valor'][1]}? [S/N] ").upper()
  95.                     if resposta == "S":
  96.                         flag = 1
  97.                         # print(f"\nA partir dos fatos fornecidos {classificatorio} = {classe}")
  98.                         print("\nÓtimo adivinhei!!!")
  99.                         print("\nAs regras aplicadas foram: ")
  100.                         print_regras(apli_regras)
  101.                         break
  102.                     elif resposta == "N":
  103.                         print(f"\nA partir dos fatos fornecidos não foi possível definir o {classificatorio}")
  104.                         flag=1
  105.                         break
  106.                     else:
  107.                         print("Digite uma resposta válida!")
  108.                         continue
  109.    
  110.                 elif i["valor"] not in fatos:
  111.                     fatos.append(i["valor"])
  112.                     ind = temp_atributos.index(i['valor'][0])
  113.                     temp_atributos.pop(ind)
  114.                     temp_valores.pop(ind)
  115.         if flag == 1:
  116.             break
  117.  
  118. def encad_frente_2(fatos, apli_regras, classificatorio, base_conhecimento):
  119.     classe = None  # Inicialize a variável classe
  120.     for k, i in enumerate(base_conhecimento): #Analisando regra por regra
  121.         tam = len(i["condicao"])
  122.         for j in fatos:
  123.             for x in i["condicao"]:
  124.                 if j[0] == x[0] and j[1] == x[1]:
  125.                     tam -= 1
  126.  
  127.         if tam == 0:
  128.             apli_regras.append(k + 1)
  129.             if i["valor"][0] == classificatorio:
  130.                 classe = i["valor"][1]  # Atualize a classe se a regra corresponder ao atributo
  131.  
  132.             elif i["valor"] not in fatos:
  133.                 fatos.append(i["valor"])
  134.     if classe == None:
  135.         print(f"\nA partir dos fatos fornecidos não foi possivel definir o {classificatorio}")
  136.     else:
  137.         print(f"\nA partir dos fatos fornecidos {classificatorio} = {classe}")
  138.     print("\nAs regras aplicadas foram: ")
  139.     for i in apli_regras:
  140.         print(f"Regra {i}")
  141.  
  142.  
  143. base_conhecimento = []
  144.  
  145. qt_regras = int(input("Quantas regras serão digitadas? "))
  146.  
  147. atributos = []
  148. valores = []
  149.  
  150. for i in range(qt_regras):
  151.     regra = input(f"Regra {i + 1}: ").replace("=", "").replace(",", "").replace(".", "").split()
  152.  
  153.     dic_regra = {
  154.         "condicao": [],
  155.         "valor": []
  156.     }
  157.  
  158.     for j in range(len(regra)):
  159.         if regra[j] == "SE" or regra[j] == "E":
  160.             atributo, valor = regra[j + 1], regra[j + 2]
  161.             dic_regra["condicao"].append([atributo, valor])
  162.  
  163.             if atributo in atributos:
  164.                 k = atributos.index(atributo)
  165.                 if valor not in valores[k]:
  166.                     valores[k].append(valor)
  167.             else:
  168.                 atributos.append(atributo)
  169.                 valores.append([valor])
  170.     if "ENTÃO" in regra:
  171.         atributo, valor = regra[regra.index("ENTÃO") + 1], regra[regra.index("ENTÃO") + 2]
  172.         dic_regra["valor"] = [atributo, valor]
  173.         if atributo in atributos:
  174.             k = atributos.index(atributo)
  175.             if valor not in valores[k]:
  176.                 valores[k].append(valor)
  177.         else:
  178.             atributos.append(atributo)
  179.             valores.append([valor])
  180.  
  181.     base_conhecimento.append(dic_regra)
  182. classificatorio = input("Qual o Atributo classificatório? ")
  183.  
  184. print("\nRegras na Base de Conhecimento:")
  185. print_regras(base_conhecimento)
  186. # print("\nAtributos encontrados:")
  187. # print(atributos)
  188. # print("\nValores possíveis para cada atributo:")
  189. # for i, atributo in enumerate(atributos):
  190. #     print(f"{atributo}: {valores[i]}")
  191.  
  192. while True:
  193.     x = int(input("\n[ 1 ]  Encadeamento para Frente\n[ 2 ]  Encadeamento para Trás\n[ 0 ]  Sair\n"))
  194.     if x == 0:
  195.         break
  196.     elif x == 1:
  197.         print("ENCADEAMENTO PARA FRENTE: \n")
  198.         encad_frente(classificatorio, base_conhecimento, atributos, valores)
  199.  
  200.     elif x == 2:
  201.         print("ENCADEAMENTO PARA TRÁS: \n")
  202.         objetivo = input(f"Qual o seu objetivo para classe {classificatorio}? ")
  203.         fatos = list()
  204.         fato_objetivo = list()
  205.         fato_objetivo.append(classificatorio)
  206.         fato_objetivo.append(objetivo)
  207.         fatos.append(fato_objetivo)
  208.         n = 0
  209.         n, fatos = encad_tras(objetivo, fatos, base_conhecimento)
  210.         while n != 0:
  211.             for i in fatos:
  212.                 n, fatos = encad_tras(i, fatos, base_conhecimento)
  213.         print(f"\nPara {classificatorio} = {objetivo} serão necessários os Fatos: ")
  214.         for fato in fatos:
  215.             print(f"{fato[0]} = {fato[1]}")
  216.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement