Solver | Code !!top!! Cracker Word
while True: print("\n> ", end="") cipher = input().strip() if cipher.lower() in ('quit', 'exit', 'q'): break if not cipher: continue decoded, mapping = cracker.solve(cipher) print("\nDecoded message:") print(decoded) if mapping: print("\nCipher mapping (cipher -> plain):") for c in sorted(mapping.keys()): print(f" c.upper() -> mapping[c].upper()") else: print("\nNo mapping found — try a larger word list.") print("-" * 50) 6. Example usage (if run as script) ---------------------------------------------------------------------- if name == " main ": # Test with a famous cipher example (ROT13 actually) test_message = "Gur dhvpx oebja sbk whzcf bire gur ynml qbt" cracker = CodeCracker() result, _ = cracker.solve(test_message) print("\nTest:\n" + test_message) print("-> " + result)
def _score_text(self, text): """Score text by counting known English words.""" words = re.findall(r'[A-Za-z]+', text.lower()) score = 0 for w in words: if w in self.word_set: score += len(w) # longer words give more confidence return score 5. Interactive solver (command line) ---------------------------------------------------------------------- def main(): print("=" * 50) print("CODE CRACKER WORD SOLVER") print("Solves simple substitution ciphers (A-Z -> any letter)") print("Enter your coded message (use letters only, spaces fine):") print("(Example: 'Gur dhvpx oebja sbk whzcf bire gur ynml qbt')") print("Type 'quit' to exit.") print("=" * 50) code cracker word solver
def _consistent(self, cipher_word, plain_word, mapping): """Check if cipher_word can map to plain_word given existing mapping.""" for c, p in zip(cipher_word, plain_word): if c in mapping and mapping[c] != p: return False return True while True: print("\n> ", end="") cipher = input()
def solve(self, cipher_text): """ Solve a substitution cipher. cipher_text: string with letters (A-Z, a-z) and spaces/punctuation. Returns: (decoded_string, mapping_dict) """ # Normalize: keep uppercase for ciphertext letters, but work lowercase original = cipher_text cipher_words = re.findall(r'[A-Za-z]+', cipher_text) if not cipher_words: return cipher_text, {} # Work with lowercase cipher words cipher_words_lower = [w.lower() for w in cipher_words] # Possible mappings: cipher_char -> plain_char possible_maps = [{}] for cw in cipher_words_lower: pattern = get_word_pattern(cw) candidates = self.pattern_dict.get(pattern, []) if not candidates: # No word matches this pattern — puzzle may have errors continue # Filter candidates based on current possible mappings new_possible_maps = [] for pmap in possible_maps: for cand in candidates: if self._consistent(cw, cand, pmap): # Create new mapping extending pmap new_map = pmap.copy() valid = True for c, p in zip(cw, cand): if c in new_map: if new_map[c] != p: valid = False break else: new_map[c] = p if valid: new_possible_maps.append(new_map) possible_maps = new_possible_maps if not possible_maps: break # Choose the best mapping (most frequent letters resolved) if not possible_maps: return original, {} best_map = possible_maps[0] if len(possible_maps) > 1: # Heuristic: prefer mapping that decodes to real words best_score = -1 for pmap in possible_maps: decoded = self._apply_map(original, pmap) score = self._score_text(decoded) if score > best_score: best_score = score best_map = pmap decoded_text = self._apply_map(original, best_map) return decoded_text, best_map Pattern matching for words (e
cracker = CodeCracker()
import sys import re from collections import Counter ---------------------------------------------------------------------- 1. Build a frequency dictionary from an English word list ---------------------------------------------------------------------- def load_word_list(filename="words_alpha.txt"): """Load a list of English words (one per line).""" try: with open(filename, 'r') as f: words = [w.strip().lower() for w in f if len(w.strip()) > 1] return set(words) except FileNotFoundError: # Fallback: common short word list return set([ "a", "i", "an", "as", "at", "be", "by", "do", "go", "he", "it", "is", "me", "my", "no", "of", "on", "or", "so", "to", "up", "us", "we", "the", "and", "for", "are", "but", "not", "you", "with", "have", "from", "they", "this", "that", "was", "were", "word", "code", "crack", "solve" ]) ---------------------------------------------------------------------- 2. Pattern matching for words (e.g., "abc" pattern for "the") ---------------------------------------------------------------------- def get_word_pattern(word): """Return pattern like 0.1.2.0.3 for 'test' -> '0.1.2.0.3'.""" pattern = [] letter_map = {} next_num = 0 for ch in word: if ch not in letter_map: letter_map[ch] = str(next_num) next_num += 1 pattern.append(letter_map[ch]) return '.'.join(pattern) ---------------------------------------------------------------------- 3. Candidate word finder ---------------------------------------------------------------------- def build_pattern_dict(word_set): """Map pattern -> list of words with that pattern.""" pattern_dict = {} for w in word_set: p = get_word_pattern(w) pattern_dict.setdefault(p, []).append(w) return pattern_dict ---------------------------------------------------------------------- 4. Solve substitution cipher using word patterns ---------------------------------------------------------------------- class CodeCracker: def init (self, word_set=None): if word_set is None: word_set = load_word_list() self.word_set = word_set self.pattern_dict = build_pattern_dict(word_set)
def _apply_map(self, text, mapping): """Apply mapping to entire text (preserve case/punctuation).""" result = [] for ch in text: if ch.isalpha(): lower_ch = ch.lower() if lower_ch in mapping: new_ch = mapping[lower_ch] if ch.isupper(): new_ch = new_ch.upper() result.append(new_ch) else: result.append('?') else: result.append(ch) return ''.join(result)