我正在检查是否有两个字符串a并且b是彼此的排列,我想知道在Python中执行此操作的理想方法是什么.从Python的禅宗,"应该有一个 - 最好只有一个 - 显而易见的方式",但我看到至少有两种方式:
sorted(a) == sorted(b)
Run Code Online (Sandbox Code Playgroud)
和
all(a.count(char) == b.count(char) for char in a)
Run Code Online (Sandbox Code Playgroud)
但是第一个是慢的时候(例如)第一个char a无处可去b,而第二个是实际排列时更慢.
有更好的方法(无论是更多的Pythonic,还是平均更快的意义上)的方式呢?或者我应该从这两个中选择,具体取决于我期望最常见的情况?
以前作为一个面试问题,并且在基本语法上窒息得太厉害,我没能推进(一旦肾上腺素开始,编码就会消失.)
给定一个字符串列表,返回一组字符串列表,这些字符串是输入集的字谜.即"狗","上帝","foo"应该返回{"dog","god"}.之后,我自己创建了代码作为一个完整性检查,它现在已经存在了一段时间.我欢迎对它进行输入,看看我是否遗漏了任何东西,或者我是否可以更有效地完成任务.把它当作改善自己和学习其他技巧的机会:
void Anagram::doWork(list input, list> &output)
{
typedef list < pair < string, string>> SortType;
SortType sortedInput;
// sort each string and pair it with the original
for(list< string >::iterator i = input.begin(); i != input.end(); ++i)
{
string tempString(*i);
std::sort(tempString.begin(), tempString.end());
sortedInput.push_back(make_pair(*i, tempString));
}
// Now step through the new sorted list
for(SortType::iterator i = sortedInput.begin(); i != sortedInput.end();)
{
set< string > newSet;
// Assume (hope) we have a match and pre-add the first.
newSet.insert(i->first);
// Set …Run Code Online (Sandbox Code Playgroud) 我有一个单词列表和一个包含许多字谜的文件.这些字谜是单词列表中的单词.我需要开发一种算法来查找匹配的单词并在输出文件中生成它们.到目前为止我开发的代码只适用于前两个单词.另外,我无法让代码与包含数字的字符串一起玩得很好.请告诉我如何修复代码.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (void)
{
int x = 0, y = 0;
int a = 0, b = 0;
int emptyx, emptyy;
int match = 0;
ifstream f1, f2;
ofstream f3;
string line, line1[1500], line2[50];
size_t found;
f1.open ("wordlist.txt");
f2.open ("file.txt");
f3.open ("output.txt");
while (f1.eof() == 0)
{
getline (f1, line);
line1[x] = line;
x++;
}
while (f2.eof() == 0)
{
getline (f2, line);
line2[y] = line;
y++;
}
//finds position …Run Code Online (Sandbox Code Playgroud) 问题陈述:给你一组k个字符串,每个长度为n.你必须一起输出一组字谜.Anagrams就像是atm - mat,like-kile.