fork(1) download
  1. # Playground for https://stackoverflow.com/a/59353025/11458991
  2.  
  3.  
  4. import functools
  5. import itertools
  6. import string
  7.  
  8.  
  9. @functools.lru_cache()
  10. def f(N, K):
  11. if N == 2:
  12. return K
  13. M = (N + 1)//2
  14. return K**M - sum(K**(M - L) * f(L, K) for L in range(2, M+1))
  15.  
  16.  
  17. def is_palindrome(s):
  18. return s[:(len(s) + 1)//2] == s[len(s)//2:][::-1]
  19.  
  20.  
  21. def brutal_f(N, K):
  22. alphabet = string.ascii_lowercase[:K]
  23. ret = 0
  24. for t in itertools.product(alphabet, repeat=N):
  25. s = "".join(t)
  26. if is_palindrome(s) and not any(is_palindrome(s[:i]) for i in range(2, N)):
  27. ret += 1
  28. return ret
  29.  
  30.  
  31. print(all(
  32. f(N, K) == brutal_f(N, K)
  33. for N in range(12)
  34. for K in range(4)
  35. ))
  36.  
Success #stdin #stdout 0.17s 9560KB
stdin
Standard input is empty
stdout
True