Guest User

Magic card trick

a guest
May 29th, 2020
93
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Try it online: https://tio.run##bVNNj9owEL3nV4zCYW0V0aq9oXLtDYlDb9sKOfFk8WJsxx9o6YrfTsdOAmm1kSJ55o3fmy@7SzxY8@22hQ3UomllXSU6fq322bGvq0qEgD6CRsMCRrblHDabYm75BH6B75DoH7y3ztsTqEiItTqAOjlLQQ79KUURlTVhCa09NcoMVlXtSE2rENk8KGtVlcQOnA1BNRr3Z6ETBub4ugKo61poPYJKq6gwQLTQaeUonVZ4SeIGHAVSeGd9gfbKSNVigeZZMC/MC7Jcg@N8CamIAPT33Hix5zz4llnmrMMduvX8iPlNDPvivyjUEmJyGllPxXWEvF@rFFCOtZEjtzljpOMy/W49Zt@Xaj7sBYDqCDc25pgZ35TPzLUSUmb1AeieXc6vH83GozjSGXXANSxI9nM@FnSc9g9BDliQGASrU24epZeMrIZpqZCF1CjH3BL6kqPHmLwBRrOhDepXLd2JbM@BuPBNtFFf7mMTHktbHcoxMRBGwjCcaQF7Dv@D2wIm@AQhnZjYbJrSObFscl/@KEfp9LTCC7DxgH6mlkx7yAtw1wOgIVQL@HnAR50qQKmN2t0BMVAj8uXoE66n1xBo21GyrqQyGjteGBeQ2wPUJWVQAhHGzI4RbPfPA5k/u@5ecN6MbjUOnnMOj29kbtQrtlGdcSKgF8I@GkhpSz6VBV7Raz1lSqrYeUVjqX@ZevVqFcnX709Pw/HIr2u4W2d@rQvNcQnnTDMVfmfj/Hb7Cw
  2.  
  3. from itertools import permutations, combinations
  4.  
  5. M = "abcd"
  6. u = 2
  7.  
  8. P = list(permutations(M))
  9.  
  10. def possible_values(p):
  11.   """all possibilities to flip u cards in p"""
  12.   for flip_indices in combinations(range(len(p)), u):
  13.     q = list(p)
  14.     for flip_index in flip_indices:
  15.       q[flip_index] = _
  16.     yield tuple(q)
  17.  
  18. f = {}
  19. used_values = set()
  20.  
  21. for p in P:
  22.   for q in possible_values(p):
  23.     if q not in used_values:
  24.       used_values.add(q)
  25.       f[p] = q
  26.       break
  27.   else: #for/else, not if/else
  28.     assert False # no solution found
  29.  
  30.  
  31. def is_valid_value(p, q):
  32.   return ( u == q.count(_)  # exactly u cards are flipped
  33.        and len(p) == len(q)
  34.        and len(M) == u + sum(a==b for a,b in zip(p,q)) # other cards are unchanged
  35.          )
  36.  
  37.  
  38. # The solution is valid iff these are true:
  39. assert sorted(f) == sorted(P)     # f is defined on the set of permutations
  40. assert len(f) == len(set(f.values()))           # f is bijective
  41. assert all(is_valid_value(p, q) for p, q in f.items())
  42.  
  43.  
  44. print("\n".join(f"{''.join(k)}: {''.join(v)}" for k, v in sorted(f.items())))
RAW Paste Data