Advertisement
chevengur

СПРИНТ № 4 | Обработка ошибок. Исключения | Урок 6: Обработка ошибок в поисковой системе

Dec 21st, 2023
1,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.53 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cmath>
  3. #include <iostream>
  4. #include <map>
  5. #include <set>
  6. #include <string>
  7. #include <utility>
  8. #include <vector>
  9. #include <optional>
  10.  
  11. using namespace std;
  12.  
  13. const int MAX_RESULT_DOCUMENT_COUNT = 5;
  14.  
  15. string ReadLine() {
  16.     string s;
  17.     getline(cin, s);
  18.     return s;
  19. }
  20.  
  21. int ReadLineWithNumber() {
  22.     int result;
  23.     cin >> result;
  24.     ReadLine();
  25.     return result;
  26. }
  27.  
  28. vector<string> SplitIntoWords(const string& text) {
  29.     vector<string> words;
  30.     string word;
  31.     for (const char c : text) {
  32.         if (c == ' ') {
  33.             if (!word.empty()) {
  34.                 words.push_back(word);
  35.                 word.clear();
  36.             }
  37.         } else {
  38.             word += c;
  39.         }
  40.     }
  41.     if (!word.empty()) {
  42.         words.push_back(word);
  43.     }
  44.  
  45.     return words;
  46. }
  47.  
  48. struct Document {
  49.     Document() = default;
  50.  
  51.     Document(int id, double relevance, int rating)
  52.         : id(id)
  53.         , relevance(relevance)
  54.         , rating(rating) {
  55.     }
  56.  
  57.     int id = 0;
  58.     double relevance = 0.0;
  59.     int rating = 0;
  60. };
  61.  
  62. template <typename StringContainer>
  63. set<string> MakeUniqueNonEmptyStrings(const StringContainer& strings) {
  64.     set<string> non_empty_strings;
  65.     for (const string& str : strings) {
  66.         if (!str.empty()) {
  67.             non_empty_strings.insert(str);
  68.         }
  69.     }
  70.     return non_empty_strings;
  71. }
  72.  
  73. enum class DocumentStatus {
  74.     ACTUAL,
  75.     IRRELEVANT,
  76.     BANNED,
  77.     REMOVED,
  78. };
  79.  
  80. class SearchServer {
  81. public:
  82.  
  83.     inline static constexpr int INVALID_DOCUMENT_ID = -1;
  84.  
  85.     template <typename StringContainer>
  86.     explicit SearchServer(const StringContainer& stop_words)
  87.         : stop_words_(MakeUniqueNonEmptyStrings(stop_words)) {
  88.         for(const auto& stop_word: stop_words_){
  89.             if(IsValidWord(stop_word) == false){
  90.                 throw std::invalid_argument("invalid argument");
  91.             }
  92.         }
  93.     }
  94.  
  95.     explicit SearchServer(const string& stop_words_text)
  96.         : SearchServer(
  97.             SplitIntoWords(stop_words_text))  // Invoke delegating constructor from string container
  98.     {
  99.     }
  100.  
  101.     void AddDocument(int document_id, const string& document, DocumentStatus status,
  102.                                    const vector<int>& ratings) {
  103.         if (document_id < 0) {
  104.             throw std::invalid_argument("the document is negative");
  105.         }
  106.  
  107.         if(documents_.count(document_id)){
  108.             throw std::invalid_argument("repeat document");
  109.         }
  110.  
  111.         if(IsValidWord(document)==false){
  112.             throw std::invalid_argument("invalid character");
  113.         }
  114.  
  115.         else{
  116.             const vector<string> words = SplitIntoWordsNoStop(document);
  117.             const double inv_word_count = 1.0 / words.size();
  118.             for (const string& word : words) {
  119.                 word_to_document_freqs_[word][document_id] += inv_word_count;
  120.             }
  121.             documents_.emplace(document_id, DocumentData{ComputeAverageRating(ratings), status});
  122.             document_ids.push_back(document_id);
  123.         }
  124.     }
  125.  
  126.     template <typename DocumentPredicate>
  127.     vector<Document> FindTopDocuments(const string& raw_query,
  128.                                         DocumentPredicate document_predicate) const {
  129.         if(IsValidQuery(raw_query)==false){
  130.             throw std::invalid_argument("invalid character int findtop");
  131.         }else{
  132.             const Query query = ParseQuery(raw_query);
  133.             auto matched_documents = FindAllDocuments(query, document_predicate);
  134.             sort(matched_documents.begin(), matched_documents.end(),
  135.                  [](const Document& lhs, const Document& rhs) {
  136.                      if (abs(lhs.relevance - rhs.relevance) < 1e-6) {
  137.                          return lhs.rating > rhs.rating;
  138.                      } else {
  139.                          return lhs.relevance > rhs.relevance;
  140.                      }
  141.                  });
  142.             if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT) {
  143.                 matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
  144.             }
  145.             return matched_documents;
  146.         }
  147.     }
  148.  
  149.     vector<Document> FindTopDocuments(const string& raw_query, DocumentStatus status) const {
  150.         if(IsValidQuery(raw_query)==false) {
  151.             throw std::invalid_argument("invalid character int findtop");
  152.         }else{
  153.             return FindTopDocuments(
  154.                 raw_query, [status](int document_id, DocumentStatus document_status, int rating) {
  155.                     return document_status == status;
  156.                 });
  157.         }
  158.     }
  159.  
  160.     vector<Document> FindTopDocuments(const string& raw_query) const {
  161.         if(IsValidQuery(raw_query)==false) {
  162.             throw std::invalid_argument("invalid character int findtop");
  163.         }else{
  164.             return FindTopDocuments(raw_query, DocumentStatus::ACTUAL);
  165.         }
  166.     }
  167.  
  168.     int GetDocumentCount() const {
  169.         return documents_.size();
  170.     }
  171.  
  172.     tuple<vector<string>, DocumentStatus> MatchDocument(const string& raw_query,
  173.                                      int document_id) const {
  174.         if(IsValidQuery(raw_query)==false){
  175.             throw std::invalid_argument("invalid character int findtop");
  176.         }else{
  177.             const Query query = ParseQuery(raw_query);
  178.             vector<string> matched_words;
  179.             for (const string& word : query.plus_words) {
  180.                 if (word_to_document_freqs_.count(word) == 0) {
  181.                     continue;
  182.                 }
  183.                 if (word_to_document_freqs_.at(word).count(document_id)) {
  184.                     matched_words.push_back(word);
  185.                 }
  186.             }
  187.             for (const string& word : query.minus_words) {
  188.                 if (word_to_document_freqs_.count(word) == 0) {
  189.                     continue;
  190.                 }
  191.                 if (word_to_document_freqs_.at(word).count(document_id)) {
  192.                     matched_words.clear();
  193.                     break;
  194.                 }
  195.             }
  196.             auto result = tuple{matched_words, documents_.at(document_id).status};
  197.             return result;
  198.         }
  199.     }
  200.  
  201.     int GetDocumentId(const int index) const {
  202.         return document_ids.at(index);
  203.     }
  204.  
  205. private:
  206.     struct DocumentData {
  207.         int rating;
  208.         DocumentStatus status;
  209.     };
  210.     const set<string> stop_words_;
  211.     map<string, map<int, double>> word_to_document_freqs_;
  212.     map<int, DocumentData> documents_;
  213.     vector<int> document_ids;
  214.  
  215.     bool IsStopWord(const string& word) const {
  216.         return stop_words_.count(word) > 0;
  217.     }
  218.  
  219.     vector<string> SplitIntoWordsNoStop(const string& text) const {
  220.         vector<string> words;
  221.         for (const string& word : SplitIntoWords(text)) {
  222.             if (!IsStopWord(word)) {
  223.                 words.push_back(word);
  224.             }
  225.         }
  226.         return words;
  227.     }
  228.  
  229.     static int ComputeAverageRating(const vector<int>& ratings) {
  230.         if (ratings.empty()) {
  231.             return 0;
  232.         }
  233.         int rating_sum = 0;
  234.         for (const int rating : ratings) {
  235.             rating_sum += rating;
  236.         }
  237.         return rating_sum / static_cast<int>(ratings.size());
  238.     }
  239.  
  240.     struct QueryWord {
  241.         string data;
  242.         bool is_minus;
  243.         bool is_stop;
  244.     };
  245.  
  246.     QueryWord ParseQueryWord(string text) const {
  247.         bool is_minus = false;
  248.         QueryWord result;
  249.         // Word shouldn't be empty
  250.         if (text[0] == '-') {
  251.             is_minus = true;
  252.             text = text.substr(1);
  253.         }
  254.         result = {text, is_minus, IsStopWord(text)};
  255.         return result;
  256.     }
  257.  
  258.     struct Query {
  259.         set<string> plus_words;
  260.         set<string> minus_words;
  261.     };
  262.  
  263.     Query ParseQuery(const string& text) const {
  264.         Query query;
  265.         for (const string& word : SplitIntoWords(text)) {
  266.             const QueryWord query_word = ParseQueryWord(word);
  267.             if (!query_word.is_stop) {
  268.                 if (query_word.is_minus) {
  269.                     query.minus_words.insert(query_word.data);
  270.                 } else {
  271.                     query.plus_words.insert(query_word.data);
  272.                 }
  273.             }
  274.         }
  275.         return query;
  276.     }
  277.  
  278.     // Existence required
  279.     double ComputeWordInverseDocumentFreq(const string& word) const {
  280.         return log(GetDocumentCount() * 1.0 / word_to_document_freqs_.at(word).size());
  281.     }
  282.  
  283.     template <typename DocumentPredicate>
  284.     vector<Document> FindAllDocuments(const Query& query,
  285.                                       DocumentPredicate document_predicate) const {
  286.         map<int, double> document_to_relevance;
  287.         for (const string& word : query.plus_words) {
  288.             if (word_to_document_freqs_.count(word) == 0) {
  289.                 continue;
  290.             }
  291.             const double inverse_document_freq = ComputeWordInverseDocumentFreq(word);
  292.             for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) {
  293.                 const auto& document_data = documents_.at(document_id);
  294.                 if (document_predicate(document_id, document_data.status, document_data.rating)) {
  295.                     document_to_relevance[document_id] += term_freq * inverse_document_freq;
  296.                 }
  297.             }
  298.         }
  299.  
  300.         for (const string& word : query.minus_words) {
  301.             if (word_to_document_freqs_.count(word) == 0) {
  302.                 continue;
  303.             }
  304.             for (const auto [document_id, _] : word_to_document_freqs_.at(word)) {
  305.                 document_to_relevance.erase(document_id);
  306.             }
  307.         }
  308.  
  309.         vector<Document> matched_documents;
  310.         for (const auto [document_id, relevance] : document_to_relevance) {
  311.             matched_documents.push_back(
  312.                 {document_id, relevance, documents_.at(document_id).rating});
  313.         }
  314.         return matched_documents;
  315.     }
  316.  
  317.     static bool IsValidWord(const string& word) {
  318.         return none_of(word.begin(), word.end(), [](char c) {
  319.             return c >= '\0' && c < ' ';
  320.         });
  321.     }
  322.  
  323.     static bool IsValidQuery(const string& raw_query) {
  324.         if(IsValidWord(raw_query)==false) {
  325.             return false;
  326.         }
  327.         for (int i = 0; i < raw_query.size(); ++i) {
  328.             if (raw_query[i] == '-' || raw_query[raw_query.size()-1]=='-') {
  329.                 if (raw_query[i + 1] == '-' || raw_query[i + 1] == ' ') {
  330.                     return false;
  331.                 }
  332.             }
  333.         }
  334.         return true;
  335.     }
  336. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement