これらのコードを試してみましたが、何か問題があります。最初の文字列がアルファベット順かどうかを知りたいだけです。
def alp(s1):
s2=sorted(s1)
if s2 is s1:
return True
else:
return False
これは常に False を出力し、print s1 または s2 と言うと、「NameError: name 's1' is not defined」と表示されます
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:
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
sort
この答えは、 O(nlogn)に依存する答えとは対照的に、絶対的な最悪のケースで O(n) の複雑さを持ちます。
この回答を見て、任意のシーケンスで機能するものを使用できます。
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
文字列と文字列を比較していることを確認してください。
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
ors2
が文字列の場合sorted
、リストが返され、文字列とリストが比較されます。必要な比較を行うために、を使用''.join()
するとリストが取得され、すべての要素が結合され、基本的に並べ替えられた要素を表す文字列が作成されます。
次のようなものを使用します。
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