我有一个 Perl 函数,它接受时间戳并返回未更改的时间戳(如果以前从未见过),否则它会附加一些字母以使其唯一:
sub uniqify($) {
my $timestamp = shift;
state $last_ts = -1;
state $next_letter = 'A';
if ($timestamp == $last_ts) {
$timestamp .= $next_letter++;
} else {
$last_ts = $timestamp;
$next_letter = 'A';
}
return $timestamp;
}
因此,如果您使用值 1、1、1 和 2 调用它四次,它将返回 1,然后是 1A,然后是 1B,然后是 2。
注意:它只会以不断增加的时间戳被调用,所以它不需要回忆它见过的每一个,只需要回忆最后一个。
现在我需要将这个函数翻译成Python。我了解到我可以用全局变量替换“状态”变量(哎呀!)或者将它们作为属性附加到函数中,但这些都不是特别优雅。
另外,Python 没有像 Perl 神奇的自动增量那样的东西,如果你“++”一个值为“A”的变量,它就会变成“B”——或者如果它是“Z”,它就会变成“AA”。所以这也是一个曲线球。
我正在拼凑一个解决方案,但它真的很难看并且难以阅读。从 Perl 翻译成 Python 应该会产生相反的效果,对吧? :) 所以我将此作为对 SO 用户的挑战。你能把它变成一个优雅的Python函数吗?
Look at 这是将数字转换为字母数字 ID 的可靠方法的答案 https://stackoverflow.com/questions/410485/whats-the-5-character-alphanumeric-id-in-reddit-url/410504#410504
我提供的代码不是从“Z”到“AA”,而是到“BA”,但我认为这并不重要,它仍然会产生一个唯一的ID
from string import uppercase as up
import itertools
def to_base(q, alphabet):
if q < 0: raise ValueError( "must supply a positive integer" )
l = len(alphabet)
converted = []
while q != 0:
q, r = divmod(q, l)
converted.insert(0, alphabet[r])
return "".join(converted) or alphabet[0]
class TimestampUniqifier( object ):
def __init__(self):
self.last = ''
self.counter = itertools.count()
def __call__( self, str ):
if str == self.last:
suf = self.counter.next()
return str + to_base( suf, up )
else:
self.last = str
self.counter = itertools.count()
return str
timestamp_uniqify = TimestampUniqifier()
usage:
timestamp_uniqify('1')
'1'
timestamp_uniqify('1')
'1A'
timestamp_uniqify('1')
'1B'
timestamp_uniqify('1')
'1C'
timestamp_uniqify('2')
'2'
timestamp_uniqify('3')
'3'
timestamp_uniqify('3')
'3A'
timestamp_uniqify('3')
'3B'
你可以多次调用它,它仍然会产生好的结果:
for i in range(100): print timestamp_uniqify('4')
4
4A
4B
4C
4D
4E
4F
4G
4H
4I
4J
4K
4L
4M
4N
4O
4P
4Q
4R
4S
4T
4U
4V
4W
4X
4Y
4Z
4BA
4BB
4BC
4BD
4BE
4BF
4BG
4BH
4BI
4BJ
4BK
4BL
4BM
4BN
4BO
4BP
4BQ
4BR
4BS
4BT
4BU
4BV
4BW
4BX
4BY
4BZ
4CA
4CB
4CC
4CD
4CE
4CF
4CG
4CH
4CI
4CJ
4CK
4CL
4CM
4CN
4CO
4CP
4CQ
4CR
4CS
4CT
4CU
4CV
4CW
4CX
4CY
4CZ
4DA
4DB
4DC
4DD
4DE
4DF
4DG
4DH
4DI
4DJ
4DK
4DL
4DM
4DN
4DO
4DP
4DQ
4DR
4DS
4DT
4DU
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)