<jupyter_start><jupyter_text>Trouver des anagrammes d'un mot<jupyter_code>import math
import collections

import numpy as np
import pandas as pd
import matplotlib.pyplot as pp

%matplotlib inline
words = sorted({line.strip().lower() for line in open('francais.txt', 'r')})
sorted("armée")
sorted("armée") == sorted("ramée")
sorted("armée") == sorted("maré")
'-'.join(sorted("armée"))
''.join(sorted("armée"))
# compute the signature string for a word

def signature(word):
    return ''.join(sorted(word))
# brute-force anagram search: compare myword's signature
# with the signatures of all words in the dictionary

def find_anagram(myword):
    mysig = signature(myword)
    
    for word in words:
        if mysig == signature(word):
            print(word)
find_anagram('armée')
%time find_anagram('armée')
# make a dict that maps each signature to the set of words with that signature;
# each signature will map to at least one word

words_by_sig = collections.defaultdict(set)

for word in words:
    words_by_sig[signature(word)].add(word)
words_by_sig
# keep only the key/value pairs where the set has more than one element;
# this is now a regular dict

anagrams_by_sig = {sig: wordset for sig, wordset in words_by_sig.items() if len(wordset) > 1}
anagrams_by_sig
# smart anagram search: look up myword's signature, return set

def find_anagram_fast(myword):
    sig = signature(myword)
    
    return anagrams_by_sig[sig]
find_anagram_fast('arts')
find_anagram_fast('martialo')
# handle case when myword's signature is not found, returning the empty set

def find_anagram_fast(myword):
    sig = signature(myword)

    try:
        return anagrams_by_sig[sig]
    except KeyError:
        return set()
find_anagram_fast('martialo')
%time find_anagram_fast('armée')
# list of signatures, sorted by length, longest first
sorted(anagrams_by_sig.keys(), key=len, reverse=True)
# list of anagram sets, sorted by signature length
[anagrams_by_sig[sig] for sig in sorted(anagrams_by_sig.keys(), key=len, reverse=True)]
# list of anagram sets, sorted by their length, largest first
sorted(anagrams_by_sig.values(), key=len, reverse=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1045601105481345, 'fraction_numerical': 0.00046061722708429296, 'mean_word_length': 5.170454545454546, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '579396', 'license': 'MIT', 'n_tokens_mistral': 721, 'n_tokens_neox': 707, 'n_words': 222, 'path': '2.trouver des anagrames/touver des anagrammes.ipynb', 'repo_name': 'martialo12/python_data_analysis', 'size': '2171'}