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

Try It in Python: Search for a Plan چالش 7 از جلسه‌ی 37، سخت

«با پایتون امتحان کن» (اختیاری). n را (از ۲ تا ۵) بخوان. برنامه همه‌ی راه‌های جابه‌جا کردن را جست‌وجو کند و complete یا not complete چاپ کند.
تابعِ search(rooms, seen) آماده است جز وسطِ حلقه‌اش: برای دو اتاقِ a و b، اگر حیوانِ p قبلاً در اتاقِ b نبوده و حیوانِ q در اتاقِ a، جابه‌جایشان کن و با search ادامه بده؛ اگر به نتیجه رسید True برگردان.
با 4 باید complete چاپ شود.

from itertools import combinations

n = int(input())


def search(rooms, seen):
    # rooms[r]: the animal in room r; seen[p]: the rooms animal p has been in
    if all(len(s) == n for s in seen):
        return True
    for a, b in combinations(range(n), 2):
        p, q = rooms[a], rooms[b]
        # may p go to room b and q to room a? then swap and search on
        pass
    return False


start_rooms = list(range(n))
start_seen = [{p} for p in range(n)]
print("complete" if search(start_rooms, start_seen) else "not complete")

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 37: هتلِ حیوانات

بیشتر بخوان: list comprehension در پایتون: از حلقه for تا یک خط کد