Re: [问题] 如何能做到字母进位呢?

楼主: mikapauli (桜花)   2014-12-12 02:48:21
练习写看看,简单说就是让字母串和整数做对映吧。
欢迎提出建议!
def p_num(num, p):
if num < 0 or -1 <= p < 1:
raise ArithmeticError
s = []
while num:
if num % p:
s.append(num % p)
else:
s.append(p)
num -= p
num //= p
return reversed(s)
num_from_chr = lambda s, chars: sum(
map(int.__mul__,
map(chars.index,
s[::-1]),
map((len(chars)-1).__pow__,
range(len(s)))))
chr_from_num = lambda n, chars: ''.join(
map(chars.__getitem__,
p_num(n, len(chars)-1)))
from_a_to_z = tuple(map(chr, range(96, 123)))
>>> from_a_to_z
('`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
>>> num_from_chr('', from_a_to_z)
0
>>> num_from_chr('a', from_a_to_z)
1
>>> num_from_chr('z', from_a_to_z)
26
>>> num_from_chr('aa', from_a_to_z)
27
>>> num_from_chr('zz', from_a_to_z)
702
>>> num_from_chr('aaa', from_a_to_z)
703
>>> chr_from_num(0, from_a_to_z)
''
>>> chr_from_num(1, from_a_to_z)
'a'
>>> chr_from_num(26, from_a_to_z)
'z'
>>> chr_from_num(27, from_a_to_z)
'aa'
>>> chr_from_num(702, from_a_to_z)
'zz'
>>> chr_from_num(703, from_a_to_z)
'aaa'

Links booklink

Contact Us: admin [ a t ] ucptt.com