Loading

pb.py

  1. from itertools import permutations
  2.  
  3.  
  4. def solve(tab, seed=None):
  5.     if seed is None:
  6.         solutions = []
  7.     else:
  8.         solutions = seed
  9.  
  10.     candidates = ["".join(x) for x in permutations(tab) if "".join(x) not in solutions]
  11.  
  12.     for candidate in candidates:
  13.         # At least one prefix must not be the permutation of the
  14.         # prefixes of an existing solution
  15.         prefixes = [candidate[0:i] for i in range(1, len(candidate))]
  16.  
  17.         for prefix in prefixes:
  18.             # Check whether permutations of prefix are not an existing prefix
  19.             for pattern in ["".join(x) for x in permutations(prefix)]:
  20.                 if any(solution.startswith(pattern) for solution in solutions):
  21.                     break  # this prefix has a solution, try next prefix
  22.             else:
  23.                 # no permutation of prefix is the prefix of an existing solution
  24.                 solutions.append(candidate)
  25.                 break
  26.  
  27.     return solutions
  28.  
  29.  
  30. tab = '01234'
  31. rotations = [(tab[i:] + tab[:i]) for i in range(len(tab))]
  32. for x in solve(tab, rotations):
  33.     print(x)
  34.  
  35.  
  36. # 01234
  37. # 12340
  38. # 23401
  39. # 34012
  40. # 40123
  41. # 01324
  42. # 02134
  43. # 02314
  44. # 02413
  45. # 03124
  46. # 12403
  47. # 13024
  48. # 13402
  49. # 14023
  50. # 24013