我正在寫一個函數來遞增3個字母(a-z)的字符串。例如:
輸入: AAA
輸出:BAA在Python中遞增字符串
輸入: ZBA
輸出:ACA
所以順序如下
aaa
baa
...
zaa
aba
bba
cba
...
zba
aca
bca
cca
...
zca
ada
...
zzz
aaa
我寫了下面的f結next_code()
和它的作品,但我想知道是否有實現它,而不是通過個別字母串在循環更優雅的方式:
# 0 = a; 25 = z
def digit_to_char(digit):
return chr(ord('a') + digit)
# a = 0; z = 25
def char_to_digit(char):
return ord(char)-ord('a')
def next_code(code):
# if used up all codes, loop from start
if code == 'zzz':
return next_code('aaa')
else:
code = list(code)
# loop over letters and see which one we can increment
for (i, letter) in enumerate(code):
if letter == 'z':
# go on to the next letter
code[i] = 'a'
continue
else:
# increment letter
code[i] = digit_to_char(char_to_digit(letter) + 1)
return ("".join(code))
break
print (next_code('aab'))
很好的回答...你爲這個傢伙覆蓋瞭如此多的基地+1從我:) –
@JoranBeasley:TIMTOWTDI? :-)我喜歡找到他們。我從Perl開始。 – ShadowRanger
TSBO - APOO - OWTDI:P(lol) –