2

I am trying to create a alphanumeric serial number in Python, the serial number is governed by the following rules:

3-Digit Alphanumeric Series Allowed values 1-9 (Zero is excluded) and A-Z (All Capitals with exclusions of I and O) The code should be able to give the next number after getting the input number.

For example: If the input number 11D then the output number should be 11E and if the input number is 119 then output should be 12A instead of 120. Please let me know if this description is good enough to explain my requirement.

I am currently using the code mentioned below:

def next_string(self, s):
    strip_zs = s.rstrip('z')
    if strip_zs:
        return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs))
    else:
        return 'a' * (len(s) + 1)
Addy
  • 41
  • 1
  • 5
  • 1
    You actually want base conversion. We have many threads about that, e.g. http://stackoverflow.com/q/2267362/989121 – georg Apr 09 '13 at 14:58
  • 1
    Why is 119 followed by 12A and not 11A? It increased 1-2-3-...-8-9-A-B-...-Y-Z? – 000 Apr 09 '13 at 15:09
  • @JoeFrambach : I am sorry I meant 119 to be followed by 11A – Addy Apr 09 '13 at 15:23

1 Answers1

0

You can use recursion for this task:

def next_string(s):
    if len(s) == 0:
        return '1'
    head = s[0:-1]
    tail = s[-1]
    if tail == 'Z':
        return next_string(head) + '1'
    if tail == '9':
        return head+'A'
    if tail == 'H':
        return head+'J'
    if tail == 'N':
        return head+'P'
    return head + chr(ord(tail)+1)

This probably isn't the most pythonic code, but this shows how to think about it.

>>> next_string('11A')
'11B'
>>> next_string('11A')
'11B'
>>> next_string('11Z')
'121'
>>> next_string('119')
'11A'
>>> next_string('1')
'2'
>>> next_string('ZZ')
'111'
>>> next_string('ZZ1')
'ZZ2'
>>> next_string('ZZ9')
'ZZA'
>>> next_string('ZZH')
'ZZJ'
000
  • 26,951
  • 10
  • 71
  • 101
  • 1
    Umm - why does one "**need** *to use recursion*" for this? – Jon Clements Apr 09 '13 at 15:24
  • ok fine I'll change it to **can**. It's just easier for me to wrap my head around it this way. – 000 Apr 09 '13 at 15:26
  • Thanks @JoeFrambach: I would like to another thing as to how to stop the code from executing at ZZZ, currently the output is 1111 whereas I want the code to exit out at this time. – Addy Apr 09 '13 at 18:32
  • Take care of that outside of this method, when you *call* `next_string`. – 000 Apr 09 '13 at 18:34