I have been trying these code but there is something wrong. I simply want to know if the first string is alphabetical.
def alp(s1):
s2=sorted(s1)
if s2 i
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).