How can I get the next string, in alphanumeric ordering, in Python?

前端 未结 4 879
走了就别回头了
走了就别回头了 2021-01-05 23:02

I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).

f(\"aaa\")=\"aab\"
f(         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 23:40

    A different, longer, but perhaps more readable and flexible solution:

    def toval(s):
        """Converts an 'azz' string into a number"""
        v = 0
        for c in s.lower():
            v = v * 26 + ord(c) - ord('a')
        return v
    
    def tostr(v, minlen=0):
        """Converts a number into 'azz' string"""
        s = ''
        while v or len(s) < minlen:
            s = chr(ord('a') + v % 26) + s
            v /= 26
        return s
    
    def next(s, minlen=0):
        return tostr(toval(s) + 1, minlen)
    
    s = ""
    for i in range(100):
        s = next(s, 5)
        print s
    

    You convert the string into a number where each letter represents a digit in base 26, increase the number by one and convert the number back into the string. This way you can do arbitrary math on values represented as strings of letters.

    The ''minlen'' parameter controls how many digits the result will have (since 0 == a == aaaaa).

提交回复
热议问题