gpt4 book ai didi

Python:根据使用函数的答案遵循不同的路径

转载 作者:行者123 更新时间:2023-11-30 22:42:29 25 4
gpt4 key购买 nike

我正在编写一段代码,它会询问用户几个是/否问题;根据答案,应遵循不同的路径,某些路径可能会导致另一个问题,而另一些路径可能会导致答案。

我已经用 Python 编写了这个代码,其中包含许多嵌入的 if、elif 和 else 语句,但我一直在寻找一种使用函数的更有效的方法。

有人知道我如何使用函数来:

  • 提出问题
  • 检查答案是否为是/否
  • 按照提示提出其他问题或给出答案,具体取决于具体情况。

干杯

最佳答案

您可以尝试将问题/答案路径编码为类似图形的数据结构。

以下是我的意思的示例 (qa.py):

#!/usr/bin/env python3

from abc import ABCMeta, abstractmethod


# I've made them strings for now but they can be anything you want
# For e.g. Django question models
questions = [
'Question 1',
'Question 2',
'Question 3',
'Question 4',
'Question 5',
]


# Similarly these can be anything you want
answers = [
'Answer 1',
'Answer 2',
'Answer 3',
'Answer 4',
]


# The idea is to have a collection of questions and a collection of answers
# Then, we wire them up in a graph-like structure


class Node(metaclass=ABCMeta):
@abstractmethod
def run(self):
pass

class QuestionNode(Node):
def __init__(self, question, yes_node, no_node):
self.question = question
self.yes_node = yes_node
self.no_node = no_node

def run(self):
print(self.question)

# Basic prompt for illustration purposes only
answer = None
while answer not in ['y', 'yes', 'n', 'no']:
answer = input('(y/n) > ').lower()

if answer[0] == 'y':
self.yes_node.run()
else:
self.no_node.run()


class AnswerNode(Node):
def __init__(self, answer):
self.answer = answer

def run(self):
print('Answer: ' + self.answer)


if __name__ == '__main__':
answer_nodes = [AnswerNode(answer) for answer in answers]

q4 = QuestionNode(questions[4], answer_nodes[1], answer_nodes[2])
q3 = QuestionNode(questions[3], answer_nodes[0], q4)
q2 = QuestionNode(questions[2], answer_nodes[2], answer_nodes[3])
q1 = QuestionNode(questions[1], answer_nodes[0], q3)
q0 = QuestionNode(questions[0], q1, q2)

q0.run()

并且,这是此配置的输出(我已经说明了所有可能的路径):

$ ./qa.py 
Question 1
(y/n) > y
Question 2
(y/n) > y
Answer: Answer 1

$ ./qa.py
Question 1
(y/n) > y
Question 2
(y/n) > n
Question 4
(y/n) > y
Answer: Answer 1

$ ./qa.py
Question 1
(y/n) > y
Question 2
(y/n) > n
Question 4
(y/n) > n
Question 5
(y/n) > y
Answer: Answer 2

$ ./qa.py
Question 1
(y/n) > y
Question 2
(y/n) > n
Question 4
(y/n) > n
Question 5
(y/n) > n
Answer: Answer 3

$ ./qa.py
Question 1
(y/n) > n
Question 3
(y/n) > y
Answer: Answer 3

$ ./qa.py
Question 1
(y/n) > n
Question 3
(y/n) > n
Answer: Answer 4

请注意,我将问题和答案与图形结构分开。这是有意为之,以实现最大的灵 active 。这意味着相同的问题/答案更容易出现多次,但沿着图表中的不同路径出现。

附注: 这让我想起了 Jellyvision我很久以前就遇到过的产品。

关于Python:根据使用函数的答案遵循不同的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42118936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com