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?
CodePudding user response:
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'
- go through the string from the back
- stop at the first non-"z"
- if no non-"z" is found, return all "a" (increase length)
- otherwise increment the non-"z" and reset the suffix to all "a"s
Some documentation: