Advertisement
chevengur

СПРИНТ № 2 | Шаблоны функции | Урок 4: Как устроены шаблоны

Oct 26th, 2023
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <algorithm>
  5. #include <vector>
  6. #include <cmath>
  7. using namespace std;
  8.  
  9.  
  10. template <typename Document, typename Term>
  11. vector<double> ComputeTfIdfs(const Document& documents, const Term& word){
  12.     vector<double> tfidf;
  13.     int document_count = 0;
  14.     for(const auto& document: documents){
  15.         int freq = count(document.begin(), document.end(), word);
  16.         if(freq > 0){
  17.             ++document_count;
  18.         }
  19.         tfidf.push_back(static_cast<double>(freq) / document.size());
  20.     }
  21.  
  22.     double idf = log(static_cast<double>(documents.size()) / document_count);
  23.     for(auto& tf_idf: tfidf){
  24.         tf_idf *= idf;
  25.     }
  26.     return tfidf;
  27. }
  28.  
  29. int main() {
  30.     const vector<vector<string>> documents = {
  31.         {"белый"s, "кот"s, "и"s, "модный"s, "ошейник"s},
  32.         {"пушистый"s, "кот"s, "пушистый"s, "хвост"s},
  33.         {"ухоженный"s, "пёс"s, "выразительные"s, "глаза"s},
  34.     };
  35.     const auto& tf_idfs = ComputeTfIdfs(documents, "кот"s);
  36.     for (const double tf_idf : tf_idfs) {
  37.         cout << tf_idf << " "s;
  38.     }
  39.     cout << endl;
  40.     return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement