# n = 4 f = open("four.txt","r") words = [l.rstrip("\n") for l in f] square = [""]*n def poss(d): prefs = [""]*n for i in range(d): for j in range(n): prefs[j] += square[i][j] for p in prefs: if not any(w.startswith(p) for w in words): return False return True def findsquare(d): for w in words: if w in square: continue square[d-1] = w print(square,end="\r") if poss(d): if d == n: print("Found", square) return findsquare(d+1) square[d-1] = "" findsquare(1)