Program to rearrange spaces between words in Python

Suppose we have a string s with some words that are placed among some number of spaces. Each words are separated by at least one space. We have to rearrange the spaces so that there are same number of spaces between every pair of adjacent words and the number of spaces between each word is maximized. If we are unable to redistribute all the spaces equally, we can place the extra spaces at the end.

So, if the input is like s = " I love programming ", then the output will be "I love programming ", see the spaces are distributed, between words, there are five spaces.

To solve this, we will follow these steps −

• res := blank string

• total_sp := number of spaces in s

• suff_sp_cnt := total_sp

• text_array := a list of words from s

• num_words := size of text_array

• if num_words is same as 1, then

• res := text_array[0] concatenate with total_sp number of spaces

• return res

• sep_size := quotient of total_sp /(num_words - 1)

• sep := sep_size number of spaces

• for each i in text_array - 1, do

• res := res + i

• res := res + sep

• suff_sp_cnt := suff_sp_cnt - sep_size

• suff_sp_cnt := suff_sp_cnt + sep_size

• res := remove extra spaces from left and right

• res := res concatenate suff_sp_cnt number of spaces at the end

• return res

Example (Python)

Let us see the following implementation to get better understanding −

Live Demo

def solve(s):
res = ""
total_sp = s.count(" ")
suff_sp_cnt = total_sp

text_array = s.split()
num_words = len(text_array)

if num_words == 1:
res = text_array[0] + total_sp * " "
return res

sep_size = total_sp // (num_words - 1)
sep = sep_size * " "

for i in text_array:
res += i
res += sep
suff_sp_cnt -= sep_size

suff_sp_cnt += sep_size
res = res.strip()
res += suff_sp_cnt * " "

return res

s = " I love programming "
print(solve(s))

Input

" I love programming "

Output

"I love programming "