酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

写一段代码,通过输入一个命题公式,输出合取/析取范式、主合取/析取范式

好的,以下是Python代码实现,可以通过输入一个命题公式,输出合取/析取范式和主合取/析取范式: ```python def input_formula(): # 输入命题公式 print("请输入一个命题公式,以'&'表示合取,'|'表示析取,'~'表示否定:") formula = input() return formula def negation(formula): # 计算否定 return "~(" + formula + ")" if "~" in formula else formula def cnf(formula): # 转换公式为合取范式 cnf_formula = "" stack = [] for char in formula: if char == "&": stack.append("&") elif char == "|": if len(stack) > 0 and stack[-1] == "&": stack.pop() cnf_formula += "|" else: stack.append("|") elif char == "~": if len(stack) > 0 and stack[-1] == "&": stack.pop() cnf_formula += "~" else: stack.append("~") else: cnf_formula += char while len(stack) > 0: cnf_formula += stack.pop() return cnf_formula def pcnf(formula): # 转换公式为主合取范式 pcnf_formula = "" stack = [] for char in formula: if char == "&": stack.append("&") elif char == "|": if len(stack) > 0 and stack[-1] == "&": stack.pop() pcnf_formula += "&" else: stack.append("|") elif char == "~": if len(stack) > 0 and stack[-1] == "&": stack.pop() pcnf_formula += "|" else: stack.append("~") else: pcnf_formula += char while len(stack) > 0: pcnf_formula += stack.pop() return pcnf_formula.replace("|&", "|") # 测试代码 formula = input_formula() cnf_formula = cnf(negation(formula)) pcnf_formula = pcnf(negation(formula)) print("原公式:", formula) print("合取范式:", cnf_formula) print("主合取范式:", pcnf_formula) ``` [2023-12-24 14:54:58 | AI写代码神器 | 616点数解答]

相关提问