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

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

31.03.2023, 01:55. Показов 1362. Ответов 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,894
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
Ответ Создать тему
Новые блоги и статьи
Символьное дифференцирование
igorrr37 13.02.2026
/ * Логарифм записывается как: (x-2)log(x^2+2) - означает логарифм (x^2+2) по основанию (x-2). Унарный минус обозначается как ! в-строка - входное арифметическое выражение в инфиксной(обычной). . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
Установка Qt-версии Lazarus IDE в Debian Trixie Xfce
volvo 10.02.2026
В общем, достали меня глюки IDE Лазаруса, собранной с использованием набора виджетов Gtk2 (конкретно: если набирать текст в редакторе и вызвать подсказку через Ctrl+Space, то после закрытия окошка. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru