题目如下:可以测试
http://acm.usx.edu.cn/aspnet/Question.aspx?qid=1263
代码
import re
T = int(input(''))
content = []
for i in range(T):
txt = ''
n = int(input(f''))
for j in range(n):
a = input(f'')
txt += a
content.append(txt)
for k in content:
word = re.findall(r'\w+',k)
word_dict = {i:word.count(i) for i in word}
word_list = sorted(list(word_dict.items()), key=lambda x:x[0])
word_list.sort(key=lambda x:x[1], reverse=True)
for i,j in word_list:
print(i,j)
#include<iostream>
#include<map>
#include<string>
#include<cctype>
#include<vector>
#include<algorithm>
typedef std::pair<std::string, int> WordStat;
typedef std::map<std::string, int>::iterator WordIterator;
bool cmpfunc(const WordStat& l, const WordStat& r) {
return l.second == r.second ? l.first < r.first : l.second > r.second;
}
int main()
{
int testNum;
std::cin >> testNum;
while (testNum--)
{
int lineNum;
std::cin >> lineNum;
std::cin.ignore();
std::string line;
std::map<std::string, int> wordMap;
while (lineNum--)
{
std::getline(std::cin, line);
std::string word = "";
bool lastCharIsAlpha = 0;
int i = 0;
while (i < line.size())
{
while (i < line.size() && !isalpha(line[i]))++i;
word = "";
while (i < line.size() && isalpha(line[i]))
{
word += line[i];
++i;
}
if (!word.empty())
{
wordMap[word]++;
}
}
}
std::vector<WordStat>words;
for (WordIterator iter = wordMap.begin(), iterEnd = wordMap.end(); iter != iterEnd; ++iter)
{
words.push_back(std::make_pair(iter->first, iter->second));
}
std::sort(words.begin(), words.end(), cmpfunc);
for (int i = 0; i < words.size(); ++i)
{
std::cout << words[i].first << " " << words[i].second << std::endl;
}
}
return 0;
}
已测试通过
你定义的i在第一个循环里
第二个循环里为什么会出现i
然后k循环里又出现了i,j
不仅逻辑混乱,变量也是乱用一气