shushus

Спринт 2. Как устроены шаблоны.

Dec 8th, 2022
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <map>
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. template <typename Word, typename Document>
  10. double ComputeTf(const Document& document, const Word& word) {
  11.     int word_tf = 0;
  12.     if(!document.empty()){
  13.         for (const auto& doc_word : document) {
  14.             if (doc_word == word) {
  15.                 ++word_tf;
  16.             }
  17.         }
  18.     }
  19.     return word_tf/(double)document.size();
  20. }
  21.  
  22. template <typename Word, typename Documents>
  23. double ComputeIdf(const Documents& documents, const Word& word) {
  24.     int document_freq = 0;
  25.     for (const auto& doc : documents) {
  26.         for (const auto& w : doc) {
  27.             if (w == word) {
  28.                 ++document_freq;
  29.                 break;
  30.             }
  31.         }
  32.     }
  33.     return log(documents.size()/(double)document_freq);
  34. }
  35.  
  36. template <typename Word, typename Documents>
  37. vector<double> ComputeTfIdfs(const Documents& documents, const Word& word) {
  38.     vector<double> tf_idfs;
  39.     double idf = ComputeIdf(documents, word);
  40.     for (const auto& document : documents) {
  41.         auto tf = ComputeTf(document, word);
  42.         //auto tf = count(document.begin(), document.end(), word)/(double)document.size();
  43.         tf_idfs.push_back(tf * idf);
  44.     }
  45.     return tf_idfs;
  46. }
  47.  
  48. int main() {
  49.     const vector<vector<string>> documents = {
  50.         {"белый"s, "кот"s, "и"s, "модный"s, "ошейник"s},
  51.         {"пушистый"s, "кот"s, "пушистый"s, "хвост"s},
  52.         {"ухоженный"s, "пёс"s, "выразительные"s, "глаза"s},
  53.     };
  54.     const auto& tf_idfs = ComputeTfIdfs(documents, "кот"s);
  55.     for (const double tf_idf : tf_idfs) {
  56.         cout << tf_idf << " "s;
  57.     }
  58.     cout << endl;
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment