بتل کد Battle Codeدارد باز می‌شود…

Put the Tools in Order چالش 6 از جلسه‌ی 74، سخت

تابع order_tools(goal, needs) را بنویس که ترتیب اجرای ابزارها را برای رسیدن به goal برگرداند: قبل از هر ابزار، نیازهایش (به ترتیب لیست) و نیازهای آن‌ها، و هر ابزار فقط یک بار. اگر نیازها دایره ساختند، None برگردان. خروجی:
send_message: timetable -> notes -> calc -> make_quiz -> send_message
make_quiz: timetable -> notes -> calc -> make_quiz
circle: error: the needs go in a circle

NEEDS = {
    "timetable": [],
    "notes": ["timetable"],
    "calc": [],
    "make_quiz": ["notes", "calc"],
    "send_message": ["make_quiz"],
}
CIRCLE = {"a": ["b"], "b": ["c"], "c": ["a"]}


def order_tools(goal, needs):
    order = []

    def visit(tool, path):
        # path = the tools we are in the middle of visiting
        order.append(tool)
        return True

    if not visit(goal, []):
        return None
    return order


for name, goal, needs in [("send_message", "send_message", NEEDS), ("make_quiz", "make_quiz", NEEDS), ("circle", "a", CIRCLE)]:
    order = order_tools(goal, needs)
    print(name + ":", " -> ".join(order) if order else "error: the needs go in a circle")

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 74: عامل چندابزاره

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال