Checking if a string's characters are ascending alphabetically and its ascent is evenly spaced python

前端 未结 4 1811
名媛妹妹
名媛妹妹 2020-12-12 01:09

So need to check if a string\'s characters are ascending alphabetically and if that ascent is evenly spaced.

a = \"abc\"
b = \"ceg\"

So a i

相关标签:
4条回答
  • 2020-12-12 01:18

    without itertools

    >>> a = 'abc'
    >>> ords = [ord(c) for c in a]
    >>> ords == sorted(ords)
    True
    
    >>> diffs = set()
    >>> for i in range(len(ords) -1): diffs.add(ords[i] - ords[i+1])
    >>> len(diffs) == 1
    True
    
    0 讨论(0)
  • 2020-12-12 01:19
    >>> from itertools import product
    >>> from string import lowercase
    >>> a="abc"
    >>> any(a in lowercase[i::j+1] for i,j in product(range(26),repeat=2))
    True
    >>> b="ceg"
    >>> any(b in lowercase[i::j+1] for i,j in product(range(26),repeat=2))
    True
    >>> c="longer"
    >>> any(c in string.lowercase[i::j+1] for i,j in product(range(26),repeat=2))
    False
    >>> d="bdfhj"
    >>> any(d in string.lowercase[i::j+1] for i,j in product(range(26),repeat=2))
    True
    

    It's not necessary to use product, and a little more efficient to do it this way

    >>> any(a in string.lowercase[i::j+1] for i in range(26) for j in range(26-i))
    True
    
    0 讨论(0)
  • 2020-12-12 01:22

    A non intuitive approach in handling this

    >>> somestring = "aceg"
    >>> len(set([ord(y)-ord(x) for (x,y) in zip(*(iter(somestring),) * 2) if y > x]))==1
    True
    

    The concept is to create the difference of subsequent element and see if the difference is consistent. For that I create a set and determine if the length is 1 in which case the order is preserved. Also to ensure that the series

    0 讨论(0)
  • 2020-12-12 01:32

    only hints for home work,,,

    you can try to make use of something from this

    In [100]: z = 'abc'
    In [101]: [ord(x) for x in z]
    Out[101]: [97, 98, 99]
    

    then there can be several logics to check if the elements are evenly spaced :)

    0 讨论(0)
提交回复
热议问题