بتل کد 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

راهنما

در visit: اگر tool in path بود، دایره است: return False. اگر tool in order بود، قبلاً اجرا شده: return True. وگرنه برای هر need in needs[tool]: if not visit(need, path + [tool]): return False؛ بعد order.append(tool).

یک جواب درست

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
        if tool in path:
            return False
        if tool in order:
            return True
        for need in needs[tool]:
            if not visit(need, path + [tool]):
                return False
        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")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن