CSC111 Recursive Text-Wrapping

From dftwiki3
Revision as of 14:13, 28 April 2014 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- <source lang="python"> text =""" This example involves two sets, A and B, represented here as coloured circles. The orange circle, set A, represents all living cre...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 15:13, 28 April 2014 (EDT)


text ="""
This example involves two sets, A and B, represented here
as coloured circles. The orange circle, set A, represents
all living creatures that are two-legged. The blue circle,
set B, represents the living creatures that can fly. Each
separate type of creature can be imagined as a point
somewhere in the diagram. Living creatures that both can
fly and have two legs—for example, parrots—are then in both
sets, so they correspond to points in the area where the
blue and orange circles overlap. That area contains all
such and only such living creatures. Humans and penguins
are bipedal, and so are then in the orange circle, but
since they cannot fly they appear in the left part of the
orange circle, where it does not overlap with the blue
circle. Mosquitoes have six legs, and fly, so the point for
mosquitoes is in the part of the blue circle that does not
overlap with the orange one. Creatures that are not
two-legged and cannot fly (for example, whales and spiders)
would all be represented by points outside both circles.
The combined area of sets A and B is called the union of A
and B, denoted by A ∪ B. The union in this case contains
all living creatures that are either two-legged or that can
fly (or both). The area in both A and B, where the two sets
overlap, is called the intersection of A and B, denoted by
A ∩ B. For example, the intersection of the two sets is not
empty, because there are points that represent creatures
that are in both the orange and blue circles."""

def wrap( text, length ):
    # stopping condition
    if len( text ) < length:
        return text+"\n"

    # recursive step: make the problem smaller by finding
    # the first line of the text that fits in the length
    # specify, and then recurse on the left over text.
    words = text.split()
    oneLine = ""
    for i in range( len( words ) ):
        word = words[i]
        if len(oneLine) + 1 + len(word) <= length:
            oneLine = oneLine + " " + word
        else:
            break

    # return the first line of the wrapping + the lines found by
    # wrap() called on the remaining text.
    return oneLine.strip() + "\n" + wrap( " ".join( words[i:] ), length ) 


wt = wrap( text, 50 )
print( wt )