CSC111 Recursive Text-Wrapping

From dftwiki3
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 ):
    """wraps the text at the given length.  Returns the wrapped text."""

    # stopping condition.  
    if len( text ) < length or text.find( " " )==-1:
        return text

    # cut the text into one line, of the right length, plus
    # the remaining text
    shortLine = text[0:length]
    remaining = text[length: ]
    
    # if the line doesn't end with a space, we're cutting a word
    # move the word to the beginning of the remaining text
    while shortLine[-1] != " ":
        char = shortLine[-1]
        shortLine = shortLine[0:-1]
        remaining = char + remaining

    # we're done.  Wrap the remaining text, and add it the 
    # short line, with a \n in between.  That's what we return.    
    return shortLine + "\n" + wrap( remaining, length )


def main():
      wt = wrap( text, 50 )
      print( wt )

main()