检查两个字符串是否彼此的Python排列 [英] Checking if two strings are permutations of each other in Python

查看:222
本文介绍了检查两个字符串是否彼此的Python排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查,如果两个字符串 A B 是彼此的排列,我想知道什么是理想的方式来做到这一点是在Python。从Python中的禅,应该有一个 - 和preferably只有一个 - 明显的方法来做到这一点,但我看到至少有两种方式:

I'm checking if two strings a and b are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:

sorted(a) == sorted(b)

all(a.count(char) == b.count(char) for char in a)

但第一个慢得多(例如)的第一个字符一个是无处 B ,第二是较慢时它们实际上是置换。

but the first one is slower when (for example) the first char of a is nowhere in b, and the second is slower when they are actually permutations.

有没有什么更好的方法来做到这一点(无论是在更Python的感觉,或更快的平均意义上的)?或者我应该只是这两个选择取决于我希望这情况是最常见的?

Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?

推荐答案

启发式你可能会更好基于字符串的大小来划分他们。

heuristically you're probably better to split them off based on string size.

伪code:

returnvalue = false
if len(a) == len(b)
   if len(a) < threshold
      returnvalue = (sorted(a) == sorted(b))
   else
       returnvalue = naminsmethod(a, b)
return returnvalue

如果性能是至关重要的,并且字符串大小可以是大或小,那么这是我会怎么做。

If performance is critical, and string size can be large or small then this is what I'd do.

这是常见的分裂这样的事情根据输入的尺寸或类型$ P ​​$ ptty的。算法有不同的优点和缺点,这将是愚蠢的,用一个又哪里会更好......在这种情况下,那敏的方法是O(n),但具有比o一个较大的常数因子(N log n)的排序方法。

It's pretty common to split things like this based on input size or type. Algorithms have different strengths or weaknesses and it would be foolish to use one where another would be better... In this case Namin's method is O(n), but has a larger constant factor than the O(n log n) sorted method.

这篇关于检查两个字符串是否彼此的Python排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆