J'ai actuellement du code python que je voudrais porter en C++ car il est actuellement plus lent que je ne le voudrais. Le problème est que j'utilise un dictionnaire dans lequel la clé est un tuple composé d'un objet et d'une chaîne (par exemple (obj, "mot")). Comment diable puis-je écrire quelque chose de similaire en C++? Peut-être que mon algorithme est horrible et qu'il y a un moyen de le rendre plus rapide sans avoir recours au C++?Comment implémenter un dictionnaire "avec un tuple Python" comme clé en C++?
L'algorithme entier ci-dessous pour des raisons de clarté. Le dictionnaire "post_score" est le problème.
def get_best_match_best(search_text, posts):
"""
Find the best matches between a search query "search_text" and any of the
strings in "posts".
@param search_text: Query to find an appropriate match with in posts.
@type search_text: string
@param posts: List of candidates to match with target text.
@type posts: [cl_post.Post]
@return: Best matches of the candidates found in posts. The posts are ordered
according to their rank. First post in list has best match and so on.
@returntype: [cl_post.Post]
"""
from math import log
search_words = separate_words(search_text)
total_number_of_hits = {}
post_score = {}
post_size = {}
for search_word in search_words:
total_number_of_hits[search_word] = 0.0
for post in posts:
post_score[(post, search_word)] = 0.0
post_words = separate_words(post.text)
post_size[post] = len(post_words)
for post_word in post_words:
possible_match = abs(len(post_word) - len(search_word)) <= 2
if possible_match:
score = calculate_score(search_word, post_word)
post_score[(post, search_word)] += score
if score >= 1.0:
total_number_of_hits[search_word] += 1.0
log_of_number_of_posts = log(len(posts))
matches = []
for post in posts:
rank = 0.0
for search_word in search_words:
rank += post_score[(post, search_word)] * \
(log_of_number_of_posts - log(1.0 + total_number_of_hits[search_word]))
matches.append((rank/post_size[post], post))
matches.sort(reverse=True)
return [post[1] for post in matches]
Avez-vous déjà essayé Cython? –
Sérieusement mec, si le code est déjà sans bug, pourquoi ne pas tirer parti des outils existants? Vous voyez, Joe Polski ne recommande pas de réécrire. –
@Hamish Grubijan: qui est Joe Polski et pourquoi devrais-je me soucier de ce qu'il recommande? – sbk