Created
December 21, 2011 21:32
-
-
Save eloraburns/1507806 to your computer and use it in GitHub Desktop.
The 1-liner (whitespace is unnecessary) extensible way to "increment" a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INCREMENTED_MAP = {'1': ('2', False), '0': ('1', False), '3': ('4', False), '2': ('3', False), '5': ('6', False), '4': ('5', False), '7': ('8', False), '6': ('7', False), '9': ('0', True), '8': ('9', False)} | |
# Can extend INCREMENTED_MAP with 'a': ('b', False), ... 'z': ('a', True) to get lowercase alphabetics, etc | |
def incremented(number): | |
return ''.join( | |
reversed( | |
reduce( | |
lambda (so_far, carry_in), (old_digit, (new_digit, carry_out)): | |
( | |
so_far + (new_digit if carry_in else old_digit,), | |
carry_out | |
), | |
reversed( | |
zip( | |
number, | |
map(INCREMENTED_MAP.get, number)) | |
), | |
((), True) | |
)[0] | |
) | |
) | |
tests = ( | |
'123', | |
'129', | |
'199', | |
'999', | |
) | |
for x in tests: | |
print x, incremented(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment