我一直在嘗試這些代碼,但出現錯誤。我只是想知道第一個字符串是否按字母順序排列。如何檢查字符串中的字符是否按字母順序排列
def alp(s1):
s2=sorted(s1)
if s2 is s1:
return True
else:
return False
這始終打印假,當我說打印S1或S2,它說:「NameError:名字‘S1’沒有定義」
我一直在嘗試這些代碼,但出現錯誤。我只是想知道第一個字符串是否按字母順序排列。如何檢查字符串中的字符是否按字母順序排列
def alp(s1):
s2=sorted(s1)
if s2 is s1:
return True
else:
return False
這始終打印假,當我說打印S1或S2,它說:「NameError:名字‘S1’沒有定義」
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:
確保您使用的字符串比較字符串:
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
如果s1
或s2
是一個字符串,sorted
會返回一個列表,然後,你就可以比較字符串到一個列表。爲了做你想要的比較,使用''.join()
將獲取列表並將所有元素連接在一起,實質上創建表示排序元素的字符串。
爲什麼第二個是假的 – billwild
@billwild因爲我們比較'zxyw'和'wxyz',因爲's2'不是按字母順序的。等於'wxyz'),我們得到假 – RocketDonkey
簡單的方法+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
我會做使用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
。
+1 - 不能爭辯與更好的複雜性:) – RocketDonkey
'prev = next'讀奇怪...... –
@tvdien - 它讀取有點奇怪。我會很樂意接受更好的變量名稱的建議:) – mgilson
你可以看到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
在哪一行,你得到這個錯誤? – inspectorG4dget
打印s1 - 這條線 – billwild