Created
November 17, 2022 21:06
-
-
Save les-peters/9d188625286c1ba1be852957d36ddc1b to your computer and use it in GitHub Desktop.
combine strings
This file contains 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
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