How To Check If Characters In A String Are Alphabetically Ordered
Solution 1:
is is identity testing which compares the object IDs, == is the equality testing:
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
Also note that sorted returns a list, so change it to:
if ''.join(s2) == s1:
Or
if ''.join(sorted(s2)) == s1:
Solution 2:
You could see this answer and use something which works for any sequence:
all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1))
Example:
>>> def alp(s1):
... return all(s1[i] <= s1[i+1] for i in xrange(len(s1) - 1))
...
>>> alp("test")
False
>>> alp("abcd")
True
Solution 3:
I would do it using iter to nicely get the previous element:
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
This answer has complexity O(n) in the absolute worst case as opposed to the answers which rely on sort which is O(nlogn).
Solution 4:
Make sure that you are comparing strings with strings:
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
If s1 or s2 is a string, sorted will return a list, and you will then be comparing a string to a list. In order to do the comparison you want, using ''.join() will take the list and join all the elements together, essentially creating a string representing the sorted elements.
Solution 5:
use something like this:
sorted() returns a list and you're trying to compare a list to a string, so change that list to a string first:
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
Post a Comment for "How To Check If Characters In A String Are Alphabetically Ordered"