we have a string with spaces and we have max string length, i.e.
str1 = 'we have a string with spaces and we have max string length'
b=8
And we need to divide string in rows with max b length in row, but we can divide only in space areas, so in our example it would be like:
x='
we have
a string
with
spaces
and we
have max
string
length'
and it should work for any b. I have tried to make a list from a string and check can two elements of list be less than b(but the can be 3 or 4 etc, so dont know what to do in this case). !And very important that by the task description b is actually named as 'len' , so i believe this is made to prevent using this function...
str1 = 'we have a string with spaces and we have max string length'
def WordSearch(len:int, a:str->int:
k=[]
t=str1.split(sep=' ')
z=str()
lst1 = ['wp' str(i) for i in range(len(t))]
for j in lst1:
for i in range(len(t)):
if len(j) len(t[i])<lenn:
'wp0' t[0] ' '
print(lst1)
WordSearch(len=8,a=str1)
Is it possible to fix code? or i am going completely wrong way....
CodePudding user response:
No need to reinvent the wheel:
import textwrap
output = textwrap.wrap('we have a string with spaces and we have max string length', 8)
output == ['we have', 'a string', 'with', 'spaces', 'and we', 'have max', 'string', 'length']
You can combine the items with "\n".join(output)
, print them, or any other way of your choosing.
CodePudding user response:
It looks like some algorithm exercise, anyway it just need to take care of corner cases.
str1 = 'we have a string with spaces and we have max string length'
def WordSearch(len:int, a:str):
k=[]
first_str = ''
first_len = 0
second_str = ''
second_len = 0
is_first = True
for c in a:
if c == ' ':
if is_first:
is_first = False
continue
if first_len second_len 1 > len:
k.append(first_str)
first_str = second_str
first_len = second_len
second_str = ''
second_len = 0
else:
first_str = first_str ' ' second_str
first_len = second_len 1
second_str = ''
second_len = 0
else:
if is_first:
first_str = c
first_len = 1
else:
second_str = c
second_len = 1
if second_len != 0:
if first_len != 0:
if (first_len second_len 1 > len):
k.append(first_str)
k.append(second_str)
else:
k.append(first_str ' ' second_str)
else:
k.append(second_str)
elif first_len != 0:
k.append(first_str)
result = '\r\n'.join(k)
print(result)
WordSearch(len=8,a=str1)
CodePudding user response:
If you really want to write it yourself (rather than using textwrap) then:
def reformat(s, b):
tokens = s.split()
if len(tokens) > 0 and max(map(len, tokens)) <= b:
result = [[tokens[0]]]
for token in tokens[1:]:
e = result[-1]
if len(token) sum(map(len, e)) len(e) <= b:
e.append(token)
else:
result.append([token])
return [' '.join(e) for e in result]
s = 'we have a string with spaces and we have max string length'
print(*reformat(s, 8), sep='\n')
Output:
we have
a string
with
spaces
and we
have max
string
length