0

Let's say I have an input string str and I want to increase it's value by 1 digit each loop so 'a'->'b' & 'm'->'n', and when it reaches 'z' it increases as shown in the example below.

str= "aaaaa"
output= "aaaab"

str="aaaaz"
output="aaaba"

str ="kbzzz"
output="kcaaa"

I hope you get the idea, it is sort of like a car's odometer. How to implement this function?

1 Answer 1

2

A simple approach (using a for-else loop):

def increment(s):
    for i in range(len(s)-1, -1, -1):
        if s[i] != "z":
            break
    else:
        return "a" * (len(s) + 1)
    return s[:i] + chr(ord(s[i]) + 1) + "a" * (len(s) - i - 1)

>>> increment("aaaaa")
'aaaab'
>>> increment("aaaab")
'aaaac'
>>> increment("aazz")
'abaa'
  1. go through the string from the back
  2. stop at the first non-"z"
  3. if no non-"z" is found, return all "a" (increase length)
  4. otherwise increment the non-"z" and reset the suffix to all "a"s

Some documentation:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.