2012-11-19 77 views

回答

5

is是身份測試其比較對象ID,==是平等的測試:

In [1]: s1 = "Hello World" 
In [2]: s2 = "Hello World" 

In [3]: s1 == s2 
Out[3]: True 

In [4]: s1 is s2 
Out[4]: False 

還要注意的是sorted返回一個列表,所以將其更改爲:

if ''.join(s2) == s1: 

或者

if ''.join(sorted(s2)) == s1: 
+0

沒有什麼改變相同的結果 – billwild

+0

@billwild也許字符串沒有排序:) – iabdalkader

+0

@mux:'sorted'返回列表 – SilentGhost

2

確保您使用的字符串比較字符串:

In [8]: s = 'abcdef' 

In [9]: s == ''.join(sorted(s)) 
Out[9]: True 

In [10]: s2 = 'zxyw' 

In [11]: s2 == ''.join(sorted(s2)) 
Out[11]: False 

如果s1s2是一個字符串,sorted會返回一個列表,然後,你就可以比較字符串到一個列表。爲了做你想要的比較,使用''.join()將獲取列表並將所有元素連接在一起,實質上創建表示排序元素的字符串。

+0

爲什麼第二個是假的 – billwild

+0

@billwild因爲我們比較'zxyw'和'wxyz',因爲's2'不是按字母順序的。等於'wxyz'),我們得到假 – RocketDonkey

+0

簡單的方法+1從我 –

1

使用這樣的事情:

sorted()返回一個列表和你想的列表進行比較,以一個字符串,所以首先更改名單的字符串:

In [21]: "abcd"=="".join(sorted("abcd")) 
Out[21]: True 

In [22]: "qwerty"=="".join(sorted("qwerty")) 
Out[22]: False 

#comparsion of list and a string is False 
In [25]: "abcd"==sorted("abcd") 
Out[25]: False 
4

我會做使用iter很好地得到一個元素:

def is_ordered(ss): 
    ss_iterable = iter(ss) 
    try: 
     current_item = next(ss_iterable) 
    except StopIteration: 
     #replace next line to handle the empty string case as desired. 
     #This is how *I* would do it, but others would prefer `return True` 
     #as indicated in the comments :) 
     #I suppose the question is "Is an empty sequence ordered or not?" 
     raise ValueError("Undefined result. Cannot accept empty iterable") 

    for next_item in ss_iterable: 
     if next_item < current_item: 
      return False 
     current_item = next_item 
    return True 

這個答案有絕對的最壞情況複雜度爲O(n),而不是在寫回信依賴於O(nlogn)的sort

+2

+1 - 不能爭辯與更好的複雜性:) – RocketDonkey

+0

'prev = next'讀奇怪...... –

+0

@tvdien - 它讀取有點奇怪。我會很樂意接受更好的變量名稱的建議:) – mgilson

4

你可以看到this answer和使用的東西,這對於任何序列:

all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1)) 

例子:

>>> def alp(s1): 
...  return all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1)) 
... 
>>> alp("test") 
False 
>>> alp("abcd") 
True 
+0

這是可行的,因爲字符串是可索引的。但它不適用於任意迭代器:'iter('foobar')'。除此之外,我認爲這是一個很好的答案 - 比分類好得多。 +1 – mgilson

+0

這是一個了不起的 – billwild

相關問題