Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/6: Рейтинг темы: голосов - 6, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 31.03.2023
Сообщений: 2

Класс SearchServer не проходит проверку

31.03.2023, 01:55. Показов 1324. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
/*Тест № 10 НЕ прошел проверку
причина: Неправильный ответ
подсказка: Вы неправильно фильтруете документы по статусу

Тест № 11 НЕ прошел проверку
причина: Неправильный ответ
подсказка: Вы неправильно фильтруете документы по id

Тест № 12 НЕ прошел проверку
причина: Неправильный ответ
подсказка: Вы неправильно фильтруете документы по рейтингу

Тест № 13 НЕ прошел проверку
причина: Неправильный ответ
подсказка: Вы неправильно фильтруете документы лямбдой
Задача прошла 10 из 14 проверок
Не успех(
*/


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
 
using namespace std;
 
const int MAX_RESULT_DOCUMENT_COUNT = 5;
const double ALLOWED_ERROR = 1e-6;
string ReadLine() {
    string s;
    getline(cin, s);
    return s;
}
 
int ReadLineWithNumber() {
    int result;
    cin >> result;
    ReadLine();
    return result;
}
 
vector<string> SplitIntoWords(const string& text) {
    vector<string> words;
    string word;
    for (const char c : text) {
        if (c == ' ') {
            if (!word.empty()) {
                words.push_back(word);
                word.clear();
            }
        }
        else {
            word += c;
        }
    }
    if (!word.empty()) {
        words.push_back(word);
    }
 
    return words;
}
 
struct Document {
    int id;
    double relevance;
    int rating;
};
 
enum class DocumentStatus {
    ACTUAL,
    IRRELEVANT,
    BANNED,
    REMOVED,
};
 
 
class SearchServer {
public:
    void SetStopWords(const string& text) {
        for (const string& word : SplitIntoWords(text)) {
            stop_words_.insert(word);
        }
    }
 
    void AddDocument(int document_id, const string& document, DocumentStatus status,
        const vector<int>& ratings) {
        const vector<string> words = SplitIntoWordsNoStop(document);
        const double inv_word_count = 1.0 / words.size();
        for (const string& word : words) {
            word_to_document_freqs_[word][document_id] += inv_word_count;
        }
        documents_.emplace(document_id, DocumentData{ ComputeAverageRating(ratings), status });
    }
 
 
    template <typename Function>
    vector<Document> FindTopDocuments(const string& raw_query, Function Func) const {
 
            const Query query = ParseQuery(raw_query);
 
            auto matched_documents = FindAllDocuments(query,Func);
 
            sort(matched_documents.begin(), matched_documents.end(),
                [](const Document& lhs, const Document& rhs) {
                    if (abs(lhs.relevance - rhs.relevance) < ALLOWED_ERROR) {
                        return lhs.rating > rhs.rating;
                    }
                    else {
                        return lhs.relevance > rhs.relevance;
                    }
                });
            if (matched_documents.size() > MAX_RESULT_DOCUMENT_COUNT) {
                matched_documents.resize(MAX_RESULT_DOCUMENT_COUNT);
            }
            return matched_documents;
    }
 
 
    vector<Document> FindTopDocuments(const string& raw_query) const {
        DocumentStatus status = DocumentStatus::ACTUAL;
        return FindTopDocuments(raw_query, status);
    }
 
 
    int GetDocumentCount() const {
        return static_cast<int>(documents_.size());
    }
 
    tuple<vector<string>, DocumentStatus> MatchDocument(const string& raw_query,
        int document_id) const {
        const Query query = ParseQuery(raw_query);
        vector<string> matched_words;
        for (const string& word : query.plus_words) {
            if (word_to_document_freqs_.count(word) == 0) {
                continue;
            }
            if (word_to_document_freqs_.at(word).count(document_id)) {
                matched_words.push_back(word);
            }
        }
        for (const string& word : query.minus_words) {
            if (word_to_document_freqs_.count(word) == 0) {
                continue;
            }
            if (word_to_document_freqs_.at(word).count(document_id)) {
                matched_words.clear();
                break;
            }
        }
        return { matched_words, documents_.at(document_id).status };
    }
 
private:
    struct Query {
        set<string> plus_words;
        set<string> minus_words;
    };
    struct DocumentData {
        int rating;
        DocumentStatus status;
    };
    set<string> stop_words_;
    map<string, map<int, double>> word_to_document_freqs_;
    map<int, DocumentData> documents_;
 
    bool IsStopWord(const string& word) const {
        return stop_words_.count(word) > 0;
    }
 
    vector<string> SplitIntoWordsNoStop(const string& text) const {
        vector<string> words;
        for (const string& word : SplitIntoWords(text)) {
            if (!IsStopWord(word)) {
                words.push_back(word);
            }
        }
        return words;
    }
 
    static int ComputeAverageRating(const vector<int>& ratings) {
        if (ratings.empty()) {
            return 0;
        }
        int rating_sum = 0;
        for (const int rating : ratings) {
            rating_sum += rating;
        }
        return rating_sum / static_cast<int>(ratings.size());
    }
 
    struct QueryWord {
        string data;
        bool is_minus;
        bool is_stop;
    };
 
    QueryWord ParseQueryWord(string text) const {
        bool is_minus = false;
        // Word shouldn't be empty
        if (text[0] == '-') {
            is_minus = true;
            text = text.substr(1);
        }
        return { text, is_minus, IsStopWord(text) };
    }
 
    
 
    Query ParseQuery(const string& text) const {
        Query query;
        for (const string& word : SplitIntoWords(text)) {
            const QueryWord query_word = ParseQueryWord(word);
            if (!query_word.is_stop) {
                if (query_word.is_minus) {
                    query.minus_words.insert(query_word.data);
                }
                else {
                    query.plus_words.insert(query_word.data);
                }
            }
        }
        return query;
    }
 
    // Existence required
    double ComputeWordInverseDocumentFreq(const string& word) const {
        return log(GetDocumentCount() * 1.0 / word_to_document_freqs_.at(word).size());
    }
 
 
    template<typename Container,typename Function>
    vector<Document> FindAllDocuments(const Container& query,Function Func) const { // Стоит поправить метод так, чтобы он получал только предикат - Тогда не понимаю как передать сюда query
        
        if constexpr (is_same_v<Function, DocumentStatus>) {
            auto status = Func;
            map<int, double> document_to_relevance;
            for (const string& word : query.plus_words) {
                if (word_to_document_freqs_.count(word) == 0) {
                    continue;
                }
                const double inverse_document_freq = ComputeWordInverseDocumentFreq(word);
                for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) {
                    if (documents_.at(document_id).status == status) {
                        document_to_relevance[document_id] += term_freq * inverse_document_freq;
                    }
                }
            }
 
            for (const string& word : query.minus_words) {
                if (word_to_document_freqs_.count(word) == 0) {
                    continue;
                }
                for (const auto [document_id, _] : word_to_document_freqs_.at(word)) {
                    document_to_relevance.erase(document_id);
                }
            }
            vector<Document> matched_documents;
            for (const auto [document_id, relevance] : document_to_relevance) {
                matched_documents.push_back(
                    { document_id, relevance, documents_.at(document_id).rating });
            }
            return matched_documents;
        }
        else {  // Как проверить является ли переданная функция функцией которая подходит нам по формату а не рандомным набором символов или переменной я так и не понял =(
            auto status = DocumentStatus::ACTUAL;
            map<int, double> document_to_relevance;
            for (const string& word : query.plus_words) {
                if (word_to_document_freqs_.count(word) == 0) {
                    continue;
                }
                const double inverse_document_freq = ComputeWordInverseDocumentFreq(word);
                for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) {
                    if (documents_.at(document_id).status == status) {
                        document_to_relevance[document_id] += term_freq * inverse_document_freq;
                    }
                }
            }
 
            for (const string& word : query.minus_words) {
                if (word_to_document_freqs_.count(word) == 0) {
                    continue;
                }
                for (const auto [document_id, _] : word_to_document_freqs_.at(word)) {
                    document_to_relevance.erase(document_id);
                }
            }
            vector<Document> matched_documents;
            for (const auto [document_id, relevance] : document_to_relevance) {
                matched_documents.push_back(
                    { document_id, relevance, documents_.at(document_id).rating });
            }
            vector<Document> filteredDocuments;
            for (const auto& elem : matched_documents) {
                if (Func(elem.id, documents_.at(elem.id).status, elem.rating)) {
                    filteredDocuments.push_back(elem);
                }
            }
 
            return filteredDocuments;
        }
       
    }
};
 
 
// ==================== для примера =========================
 
void PrintDocument(const Document& document) {
    cout << "{ "s
        << "document_id = "s << document.id << ", "s
        << "relevance = "s << document.relevance << ", "s
        << "rating = "s << document.rating
        << " }"s << endl;
}
int main() {
    SearchServer search_server;
    search_server.SetStopWords("и в на"s);
    search_server.AddDocument(0, "белый кот и модный ошейник"s, DocumentStatus::ACTUAL, { 8, -3 });
    search_server.AddDocument(1, "пушистый кот пушистый хвост"s, DocumentStatus::ACTUAL, { 7, 2, 7 });
    search_server.AddDocument(2, "ухоженный пёс выразительные глаза"s, DocumentStatus::ACTUAL, { 5, -12, 2, 1 });
    search_server.AddDocument(3, "ухоженный скворец евгений"s, DocumentStatus::BANNED, { 9 });
    cout << "ACTUAL by default:"s << endl;
    for (const Document& document : search_server.FindTopDocuments("пушистый ухоженный кот"s)) {
        PrintDocument(document);
    }
    cout << "BANNED:"s << endl;
    for (const Document& document : search_server.FindTopDocuments("пушистый ухоженный кот"s, DocumentStatus::BANNED)) {
        PrintDocument(document);
    }
    cout << "Even ids:"s << endl;
    for (const Document& document : search_server.FindTopDocuments("пушистый ухоженный кот"s, [](int document_id, DocumentStatus, int) { return document_id % 2 == 0; }))
    {
        PrintDocument(document);
    }
  
    return 0;
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
31.03.2023, 01:55
Ответы с готовыми решениями:

почему не проходит проверку?
#include &quot;stdafx.h&quot; #include &quot;stdio.h&quot; #include &quot;string&quot; #include &quot;conio.h&quot; #define NMAX 4 void vvod(double m, char name) ...

Не проходит проверку
Здравствуйте. Не пойму почему не работает проверка на условие. //...код Если ВыборкаДетальныеЗаписи.Следующий() Тогда //...код ...

Почему не проходит проверку?
Собственно задача: Входные данные Первая строка содержит целые числа N, M и K...

2
31.03.2023, 05:57

Не по теме:

Н-да... Тут все в курсе именно вашей задачи.

0
Эксперт С++
 Аватар для schdub
3073 / 1411 / 425
Регистрация: 19.01.2009
Сообщений: 3,893
31.03.2023, 16:59
Цитата Сообщение от IML420 Посмотреть сообщение
if constexpr (is_same_v<Function, DocumentStatus>) {
IML420, итоговый проект 3го спринта вроде?

Зачем вы сравниваете тип 2го аргумета ? они точно не равны. Нам передают лямбду.

Цитата Сообщение от IML420 Посмотреть сообщение
Стоит поправить метод так, чтобы он получал только предикат - Тогда не понимаю как передать сюда query
Так прям в задании написано?
Год назад учился там же, у меня функция
C++
1
2
template<typename Predicate>
vector<Document> FindAllDocuments(const Query& query, Predicate predicate) const
принимает 2 аргумента:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
template<typename Predicate> 
vector<Document> FindAllDocuments(const Query& query, Predicate predicate) const { 
    map<int, double> document_to_relevance; 
    for (const string& word : query.plus_words) { 
        if (word_to_document_freqs_.count(word) == 0) { 
            continue; 
        } 
 
        const double inverse_document_freq = ComputeWordInverseDocumentFreq(word); 
        for (const auto [document_id, term_freq] : word_to_document_freqs_.at(word)) { 
            const DocumentData & doc_data = documents_.at(document_id); 
            if ( predicate(document_id, doc_data.status, doc_data.rating) ) { 
                document_to_relevance[document_id] += term_freq * inverse_document_freq; 
            } 
        } 
    } 
 
    for (const string& word : query.minus_words) { 
        if (word_to_document_freqs_.count(word) == 0) { 
            continue; 
        } 
        for (const auto [document_id, _] : word_to_document_freqs_.at(word)) { 
            document_to_relevance.erase(document_id); 
        } 
    } 
 
    vector<Document> matched_documents; 
    for (const auto [document_id, relevance] : document_to_relevance) { 
        matched_documents.push_back({ 
            document_id, 
            relevance, 
            documents_.at(document_id).rating 
        }); 
    } 
    return matched_documents; 
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
31.03.2023, 16:59
Помогаю со студенческими работами здесь

MaskedTextBox не проходит проверку на пустоту
Приветствую всех. Это опять я. Я же не знал, что в программировании столько всяких нюансов и проблем. Так вот. На форме есть...

Mfrac не проходит проверку валидатора
Добрый день. &lt;div&gt;&lt;mfrac&gt;&lt;mn&gt;x&lt;/mn&gt;&lt;mn&gt;y&lt;/mn&gt;&lt;/mfrac&gt;&lt;/div&gt; &lt;span&gt;&lt;mfrac&gt;&lt;mn&gt;x&lt;/mn&gt;&lt;mn&gt;y&lt;/mn&gt;&lt;/mfrac&gt;&lt;/span&gt; Код не проходит проверку...

Не проходит проверку логина и пароля
Добрый день, написал такой код для проверки занятости логина и мыла. &quot;use strict&quot;; $(document).ready(function () { ...

Не проходит проверку метод пост
Всем привет подскажите почему не проходит проверку на method==post? views.py: def post_share(request, post_id): post =...

Комп не проходит проверку оборудования
Ребята, помогите пожалуйста!!!! Комп иногда(часто) не может пройти проверку оборудования. Поправляю шлейф от винта- начинает грузится!...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru