相关疑难解决方法(0)

分组anagram词的算法

给定一组单词,我们需要找到anagram单词并使用最佳算法单独显示每个类别.

输入:

man car kile arc none like
Run Code Online (Sandbox Code Playgroud)

输出:

man
car arc
kile like
none
Run Code Online (Sandbox Code Playgroud)

我现在开发的最佳解决方案是基于散列表,但我正在考虑将anagram字转换为整数值的等式.

示例:man =>'m'+'a'+'n'但这不会给出唯一值.

有什么建议吗?


请参阅C#中的以下代码:

string line = Console.ReadLine();
string []words=line.Split(' ');
int[] numbers = GetUniqueInts(words);
for (int i = 0; i < words.Length; i++)
{
    if (table.ContainsKey(numbers[i]))
    {
        table[numbers[i]] = table[numbers[i]].Append(words[i]);
    }
    else
    {
        table.Add(numbers[i],new StringBuilder(words[i]));
    }

}
Run Code Online (Sandbox Code Playgroud)

问题是如何开发GetUniqueInts(string [])方法.

algorithm data-processing anagram

19
推荐指数
3
解决办法
2万
查看次数

你可以用给定单词的字母制作4个字母或更多的常用英文单词(每个字母只能使用一次)

在块日历的背面,我发现了以下谜语:

你可以用"教科书"这个词的字母做出多少4个字母或更多的常用英文单词(每个字母只能使用一次).

我想出的第一个解决方案是:

from itertools import permutations

with open('/usr/share/dict/words') as f:
    words = f.readlines()

words = map(lambda x: x.strip(), words)

given_word = 'textbook'

found_words = []

ps = (permutations(given_word, i) for i in range(4, len(given_word)+1))

for p in ps:
    for word in map(''.join, p):
        if word in words and word != given_word:
            found_words.append(word)
print set(found_words)  
Run Code Online (Sandbox Code Playgroud)

这给出了结果,set(['tote', 'oboe', 'text', 'boot', 'took', 'toot', 'book', 'toke', 'betook'])但在我的机器上花费了超过7分钟.

我的下一次迭代是:

with open('/usr/share/dict/words') as f:
    words = f.readlines()

words = map(lambda x: x.strip(), words) …
Run Code Online (Sandbox Code Playgroud)

python puzzle algorithm permutation

7
推荐指数
1
解决办法
2213
查看次数

为什么`word == word [:: - 1]`比Python中更多的算法解决方案更快地测试回文?

我写了一篇关于Code Review的问题的灾难,询问为什么Python程序员通常通过比较字符串与自身的反转来测试字符串是否为回文,而不是更复杂的算法,假设正常方式会更快.

这是pythonic方式:

def is_palindrome_pythonic(word):
    # The slice requires N operations, plus memory
    # and the equality requires N operations in the worst case
    return word == word[::-1]
Run Code Online (Sandbox Code Playgroud)

以下是我尝试以更有效的方式完成此任务:

def is_palindrome_normal(word):
    # This requires N/2 operations in the worst case
    low = 0
    high = len(word) - 1
    while low < high:
        if word[low] != word[high]:
            return False
        low += 1
        high -= 1
    return True
Run Code Online (Sandbox Code Playgroud)

我希望正常的方式比pythonic方式更快.例如,请参阅这篇精彩文章

timeit然而,与它同步,带来了完全相反的结果:

setup = '''
def is_palindrome_pythonic(word):
    # ...

def is_palindrome_normal(word):
    # …
Run Code Online (Sandbox Code Playgroud)

python performance

1
推荐指数
1
解决办法
78
查看次数