cryptic-cypher-machine-optimization


SUBMITTED BY: okpalan86

DATE: March 1, 2024, 3:16 p.m.

FORMAT: Text only

SIZE: 3.1 kB

HITS: 359

  1. class TrieNode:
  2. def __init__(self):
  3. self.children = {}
  4. self.is_end_of_word = False
  5. class Trie:
  6. def __init__(self):
  7. self.root = TrieNode()
  8. def insert(self, word):
  9. node = self.root
  10. for char in word:
  11. if char not in node.children:
  12. node.children[char] = TrieNode()
  13. node = node.children[char]
  14. node.is_end_of_word = True
  15. def search(self, word):
  16. node = self.root
  17. for char in word:
  18. if char not in node.children:
  19. return False
  20. node = node.children[char]
  21. return node.is_end_of_word
  22. def starts_with_prefix(self, prefix):
  23. node = self.root
  24. for char in prefix:
  25. if char not in node.children:
  26. return False
  27. node = node.children[char]
  28. return True
  29. class CrypticStateMachine:
  30. def __init__(self):
  31. self.trie = Trie()
  32. def encrypt(self, message, shift):
  33. """
  34. Encrypts the message using Caesar cipher with the given shift.
  35. """
  36. encrypted_message = ""
  37. for char in message:
  38. if char.isalpha():
  39. ascii_offset = ord('a') if char.islower() else ord('A')
  40. encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
  41. encrypted_message += encrypted_char
  42. self.trie.insert(encrypted_char)
  43. else:
  44. encrypted_message += char
  45. return encrypted_message
  46. def decrypt(self, encrypted_message, shift):
  47. """
  48. Decrypts the encrypted message using Caesar cipher with the given shift.
  49. """
  50. decrypted_message = ""
  51. for char in encrypted_message:
  52. if char.isalpha():
  53. ascii_offset = ord('a') if char.islower() else ord('A')
  54. decrypted_message += chr((ord(char) - ascii_offset - shift) % 26 + ascii_offset)
  55. else:
  56. decrypted_message += char
  57. return decrypted_message
  58. def all_encryptions(self, message):
  59. """
  60. Generates all possible encrypted messages for the given input message.
  61. """
  62. for shift in range(26):
  63. yield self.encrypt(message, shift)
  64. def search_encrypted_message(self, prefix):
  65. """
  66. Searches for encrypted messages starting with the given prefix.
  67. """
  68. return self.trie.starts_with_prefix(prefix)
  69. # Usage
  70. cryptic_state_machine = CrypticStateMachine()
  71. message = "I never said she stole my money"
  72. all_encrypted_messages = list(cryptic_state_machine.all_encryptions(message))
  73. for i, encrypted_message in enumerate(all_encrypted_messages):
  74. print(f"Shift {i}: {encrypted_message}")
  75. # Example search for encrypted messages starting with a prefix
  76. print(cryptic_state_machine.search_encrypted_message("J of")) # True
  77. print(cryptic_state_machine.search_encrypted_message("X il")) # False

comments powered by Disqus