Wrap text in a list
I’m trying to write a function that accepts some text and a list, and then executes it if the last element in the list is small enough that it can append the text to the last element and is still less than 10 characters. Otherwise, append it separately to the list. The problem I’m having is if the text is 25 characters long.
For example,
l = ["12345678", "123456789"]
>>> a("a", l)
["12345678", "123456789a"]
>>> a("123456789123456789123", l)
["12345678", "1234567891", "2345678912", "3456789123"]
This is my current situation
def a(st, lst):
last = 10 - len(lst[-1])
if last < len(st):
lst[-1] += st[:last]
lst.append(st[last:])
else:
lst[-1] += st
Solution
The problem is that st
(in your given function) can be arbitrarily long, so you have to add any number of elements. Now, if something is arbitrary, a loop (for
or while) is usually called
)。
The algorithm itself consists of two stages: in the first stage, we check how much space is left in the last element of the LST
. We fill the element with (part of) st
. You can do this:
left = 10-len(lst[-1])
lst[-1] += st[:left]
Note that if is not
needed here: it will not add any characters if there is no space left, and if
there are too few characters in st>
The slice will simply return a substring.
Now we just need to add the remaining characters to the lst
in groups of 10. We can do this by writing a for
loop starting with left (since we can omit the first left
character) and jump 10 positions until it reaches the end of the
st
ring:
for i in range(left,len(st),10):
# ... do something
pass
It is clear what we have to do: add slice st[i:i+10]
to lst
. So we turn the for
loop to:
for i in range(left,len(st),10):
lst.append(st[i:i+10])
In the end we just need to return to LST
. Put them together and we get:
def a(st, lst):
# phase 1
left = 10-len(lst[-1])
lst[-1] += st[:left]
#phase 2
for i in range(left,len(st),10):
lst.append(st[i:i+10])
return lst
Note that this solution runs on the given list. If you want to make a copy, you can add a line:
def a(st, lst):
<b># make copy</b>
<b>lst = list(lst)</b>
# phase 1
left = 10-len(lst[-1])
lst[-1] += st[:left]
#phase 2
for i in range(left,len(st),10):
lst.append(st[i:i+10])
return lst