in python: Write a function that divides a phrase into word buckets, with each bucket…
- User
in python:
Write a function that divides a phrase into word buckets, with each bucket containing n or fewer characters. Only include full words inside each bucket.
Examples split_into_buckets("she sells sea shells by the sea", 10) ➞ ["she sells", "sea shells", "by the sea"]
split_into_buckets("the mouse jumped over the cheese", 7) ➞ ["the", "mouse", "jumped", "over", "the", "cheese"]
split_into_buckets("fairy dust coated the air", 20) ➞ ["fairy dust coated", "the air"]
split_into_buckets("a b c d e", 2) ➞ ["a", "b", "c", "d", "e"] Notes Spaces count as one character. Trim beginning and end spaces for each word bucket (see final example). If buckets are too small to hold a single word, return an empty list: [] The final goal isn't to return just the words with a length equal (or lower) to the given n, but to return the entire given phrase bucketized (if possible). So, for the specific case of "by" the only word with a proper length, the phrase can't be bucketized, and the returned list has to be empty.
- Assistant
Here's a Python function that performs the desired bucketization of the given phrase. The function iterates over each word in the phrase and adds it to the current bucket until the limit
nis reached, then starts a new bucket:def split_into_buckets(phrase, n): words = phrase.split() buckets = [] current_bucket = [] for word in words: if len(word) > n: # If a single word is larger than the limit, return an empty list return [] # Check if adding this word to the current bucket would exceed the limit if sum(len(w) for w in current_bucket) + len(current_bucket) + len(word) > n: # Add the current bucket to the buckets list if it has any words in it if current_bucket: buckets.append(' '.join(current_bucket)) current_bucket = [] # Add the current word to the bucket current_bucket.append(word) # Add the last bucket if it contains any words if current_bucket: buckets.append(' '.join(current_bucket)) return buckets # Examples print(split_into_buckets("she sells sea shells by the sea", 10)) # ➞ ["she sells", "sea shells", "by the sea"] print(split_into_buckets("the mouse jumped over the cheese", 7)) # ➞ ["the", "mouse", "jumped", "over", "the", "cheese"] print(split_into_buckets("fairy dust coated the air", 20)) # ➞ ["fairy dust coated", "the air"] print(split_into_buckets("a b c d e", 2)) # ➞ ["a", "b", "c", "d", "e"]This function takes a phrase and a bucket size limit
n, splits the phrase into words, and then aggregates these words into buckets where each bucket's character length is less than or equal ton. If a single word exceedsncharacters, the function returns an empty list, as specified in the requirements.