سؤال

I've written a small script that creates a new line break after a certain character limit has been reached. Now the problem is that the script outputs the text starting at the end of the text. I can't seem to figure out how to make the text print out in the correct order without making the script more complicated. I'm doing this an exercise to better understand recursion.

Here is the code:

def insertNewlines(text, lineLength):

    if len(text) <= lineLength:
        return text
    else:
        return insertNewlines(text[lineLength:], lineLength) + '\n' + text[:lineLength]

Here is the test output for a lineLength of 15:

length.  
e desired line   
s or exceeds th  
ord that reache  
n' after each w  
e character  '\  
Insert a newlin  
ewriter would.   
e text as a typ  
length, wrap th  
a desired line   
Given text and  

The actual input:

text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character  '\\n' after each word that reaches or exceeds the desired line length."

EDIT: Modified the code based on the suggestion below so that it wraps the words correctly:

    if len(text) <= lineLength:
    return text
elif text[lineLength] != ' ':
    return insertNewlines(text[:], lineLength + 1)
else:
    return text[:lineLength] + '\n' + insertNewlines(text[lineLength + 1:], lineLength)

Here is the new output:
Given text and a
desired line length,
wrap the text as a typewriter
would. Insert a newline character
'\n' after each word that reaches
or exceeds the desired line length.

هل كانت مفيدة؟

المحلول 2

The problem is with the order of recursive call. It should be at the tail of the function to achieve what you want. Try this:

def insertNewlines(text, lineLength):

    if len(text) <= lineLength:
        return text
    else:
        return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)

text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character  '\\n' after each word that reaches or exceeds the desired line length."
print insertNewlines(text, 15)

Output:

Given text and 
a desired line 
length, wrap th
e text as a typ
ewriter would. 
Insert a newlin
e character  '\
n' after each w
ord that reache
s or exceeds th
e desired line 
length.

نصائح أخرى

If you don't want the words to be cut off at your max width, try the textwrap library, see http://docs.python.org/2/library/textwrap.html

from textwrap import TextWrapper

text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character  '\\n' after each word that reaches or exceeds the desired line length."

tw = TextWrapper()
tw.width = 20

print "\n".join(tw.wrap(text))

[out]:

Given text and a
desired line length,
wrap the text as a
typewriter would.
Insert a newline
character  '\n'
after each word that
reaches or exceeds
the desired line
length.

Here's a native python implementation:

text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character  '\\n' after each word that reaches or exceeds the desired line length."

def wrap(txt, width):
    tmp = ""
    for i in txt.split():
        if len(tmp) + len(i) < width:
            tmp+=" "+i
        else:
            print tmp.strip()
            tmp = i

wrap(text, 20)

a more pythonic yielding method:

def wrap(txt, width):
    tmp = ""
    for i in txt.split():
        if len(tmp) + len(i) < width:
            tmp+=" "+i
        else:
            yield tmp.strip()
            tmp = i

print "\n".join(i for i in wrap(text, 20))
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top