Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created November 17, 2022 21:06
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 les-peters/9d188625286c1ba1be852957d36ddc1b to your computer and use it in GitHub Desktop.
Save les-peters/9d188625286c1ba1be852957d36ddc1b to your computer and use it in GitHub Desktop.
combine strings
question = """
Given a list of strings arr, and a max size n, return a new list where the
strings (from left to right) are joined together with a space, so that each
new string is less than or equal to the max size.
Examples:
> combineStrings(["a", "b", "c", "d", "e", "f", "g"], 5)
> ["a b c", "d e f", "g"]
> combineStrings(["a", "b", "c", "d", "e", "f", "g"], 12)
> ["a b c d e f", "g"]
> combineStrings(["alpha", "beta", "gamma", "delta", "epsilon"], 20)
> ["alpha beta gamma", "delta epsilon"]
"""
def combineStrings(arr, n):
output = []
next = ""
for i in range(0,len(arr)):
if len(next + " " + arr[i]) > n:
output.append(next.strip())
next = ""
next = next + " " + arr[i]
output.append(next.strip())
return output
print(combineStrings(["a", "b", "c", "d", "e", "f", "g"], 5))
print(combineStrings(["a", "b", "c", "d", "e", "f", "g"], 12))
print(combineStrings(["alpha", "beta", "gamma", "delta", "epsilon"], 20))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment