Skip to content

Instantly share code, notes, and snippets.

@multimentha
Created May 20, 2017 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save multimentha/9d6a3211959e4b5d392cfe7f9f457601 to your computer and use it in GitHub Desktop.
Save multimentha/9d6a3211959e4b5d392cfe7f9f457601 to your computer and use it in GitHub Desktop.
# Break this string of numbers into a sequence of 1 digit and 2 digit numbers without changing their relative order.
# Input : 1234
# Output : {1,2,34} {1,23, 4} {1,2,3,4} {12,34} {12,3,4}
def recursive_split(seq: str) -> tuple:
# check for valid strings
if not seq or len(seq) == 0:
result = [()]
# base case
elif len(seq) == 1:
result = [(seq, )]
# recursive case
else:
prefix = (seq[0], )
result = [prefix + rest for rest in recursive_split(seq[1:])]
prefix = (seq[0:2], )
result += [prefix + rest for rest in recursive_split(seq[2:])]
return result
# tests
print(recursive_split(False))
print(recursive_split('a'))
print(recursive_split('1234'))
print(recursive_split('abcdef'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment