Python:如何增加一个特殊用途的字符串?

2024-06-26 13:45:53 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑一个长度为8的特殊用途字符串,比如“a0000xy”。字符串有以下限制。在

  1. 长度=8。在
  2. 最后两个字符有特殊含义,应该保持原样。在
  3. A-Z和0-9仅为有效字符。因此正则表达式“^[A-Z0-9]{6}XY$”定义字符串。在

我如何实现一个函数,比如increment,当调用该函数时,字符串会增加一个。因此,后续调用应类似于以下内容:

>>> A = "A00000XY"
>>> print increment(A)
"A00000XY"
>>> print increment(A)
"A00001XY"
>>> print increment(A)
"A00002XY"
...
>>> print increment(A)
"A00009XY"
>>> print increment(A)
"A0000AXY"
>>> print increment(A)
"A0000BXY"
...
>>> print increment(A)
"A0000YXY"
>>> print increment(A)
"A0000ZXY"
>>> print increment(A)
"A00010XY"
>>> print increment(A)
"A00011XY"
...
>>> print increment(A)
"ZZZZZZXY"

Tags: 函数字符串定义字符用途printxy含义
3条回答

灵感来自@avysk response。在

@avysk的回复有两个问题。在

  1. 处理zzzz-xy。它应该环绕并返回000000XY。它不应该溢出。然而,我没有在问题本身中涵盖这一部分。在
  2. 000000XY未正确处理以返回000001XY。取而代之的是 返回1XY。在

在以下代码中修复了这些问题,这些代码借用了@avysk的响应。在

digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def digit_helper(num):
  while num > 0:
    yield Tape.digits[num % 36]
    num = num / 36


# This function, using the utility digit_helper, increments the string by 1.
# It produces string in following order:
#     "A00000XY", "A00000XY", "A00001XY", "A00002XY", ...,
#     "A00009XY", "A0000AXY", "A0000BXY", ...,
#     "A0000YXY", "A0000ZXY", "A00010XY", "A00011XY", ...,
#     "ZZZZZZXY", "000000XY", "000001XY", ...
# Logic:
# 1. Strip the string of last two chars.
# 2. Convert to base 36 equivalent integer and increment by one.
# 3. Convert back to Base 36 representation of incremented value.
#   3.1. [0:6] handles the overflow. Overflow happens after "ZZZZZZXY" and produces "1000000XY".
#   3.2. [::-1] reverses the string.
#   3.3. zfill(6) handles underflow, like converting integer 1 to "000001XY".
def increment(string):
  incremented = int(string[:-2], base=36) + 1
  return "".join(Tape.digit_helper(incremented))[0:6][::-1].zfill(6) + string[-2:]
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def digit_helper(num):
    while num > 0:
        yield digits[num % 36]
        num = num / 36

def increment(string):
    incremented = int(string[:-2], base=36) + 1
    return "".join(reversed(list(digit_helper(incremented)))) + "XY"

诱惑太高了。不过,不太适合做作业答题,恐怕是:D

更新:它是python2。在python3中,除法应该是num // 36。在

所以你真正想要的是一个以36为基数的数字。您将需要构建一个类似于十六进制到十进制和十进制到十六进制转换工作方式的类。在8个字符的限制下,您的值从0到36^8-1,或2821109007455。 9223372036854775807是max integer in python,所以好消息是可以将值表示为整数。在

要将字符串值转换为整数:

  1. intValue=0
  2. 循环遍历字符串中的前八个字符。在
  3. 将字符传递给返回一个0到35之间的整数的函数。我们称之为charValue
  4. intValue+=intValue*36+字符值

要从整数转换为字符串值:

  1. stringValue=特殊字符
  2. curDigit=内部值%36
  3. Int36值=Int36
  4. 查找intValue的字符串等价物(0到Z)
  5. 附加到stringValue的前面
  6. 重复上述步骤,直到intValue<;36。任何剩余字符都将为0

    显然,您还将构建递增和递减方法。

相关问题 更多 >