How to check if characters in a string are alphabetically ordered

后端 未结 5 530
面向向阳花
面向向阳花 2021-01-26 08:18

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         


        
相关标签:
5条回答
  • 2021-01-26 08:30

    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).

    0 讨论(0)
  • 2021-01-26 08:31

    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.

    0 讨论(0)
  • 2021-01-26 08:40

    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
    
    0 讨论(0)
  • 2021-01-26 08:41

    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
    
    0 讨论(0)
  • 2021-01-26 08:46

    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:
    
    0 讨论(0)
提交回复
热议问题