Python:在给定两个多字符字符串的情况下返回范围

时间:2019-06-21 15:42:52

标签: python

正在寻求帮助编写函数来执行以下操作:

输入: 两个多字符字符串,例如“ AA”和“ AD”

输出: 从第一个多字符字符串到secnod的范围。例如:“ AA”“ AD”应返回“ AA”,“ AB”,“ AC”,“ AD” 该函数也应该环绕字母,因此“ AZ”“ BB”将产生“ AZ”“ BA”“ BB”

我尝试过:

import string

alphabet = list(string.ascii_lowercase)
racks = list([i+b for i in alphabet for b in alphabet])

rn = 1
for rack in racks:
    print(rack)
    rn = rn + 1

但是这给出了每个多行字符串AA-ZZ。我希望用户能够指定最后一个字符串应该在哪里结束

1 个答案:

答案 0 :(得分:1)

我认为,最通用的解决方案涉及到字母与序列号之间的转换:

ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  
#ALPHABET = 'BCXYZ'   # you can define/restrict the symbol set any way you like
LOOKUP = { letter.upper() : i for i, letter in enumerate( ALPHABET ) }
BASE = len( ALPHABET )

def l2n(letters):
    "Convert a letter code to a serial number"
    return sum(LOOKUP[ch] * BASE ** i for i, ch in enumerate(letters[::-1].upper()))

def n2l(number, minlength=2 ):
    "Convert a serial number to a letter code"
    letters = ''
    while True:
        letters += ALPHABET[number % BASE]
        number //= BASE
        if not number and len(letters) >= minlength:
            return letters[::-1]

def sequence(first, last, minlength=None):
    """
    Generator function for letter codes (each
    at least `minlength` characters long) from
    `first` to `last` inclusive.
    """
    if minlength is None:
        minlength = min(len(first), len(last))
    for i in range(l2n(first), l2n(last) + 1):
        yield n2l(i, minlength)

# example 1
print(list(sequence('BB', 'CZ')))


# example 2 - use the generator to start anywhere and
# produce any length of sequence, without excessive
# demands on memory:
for code in sequence('XYZZY', 'ZZYZX'):
    print(code)