views:

74

answers:

1

Write a function spaced(s) that outputs spaces and a dashdot border around a string s.

The sample code, which calls spaced("Hello") would output:

  --.-.-.-.-
.            .
-   Hello    -
.            .
  -.-.-.-.-.

Please help me out with this :D. Im new to programming and im trying to learn this stuff. I dont have any programming experience so its quite a challenge to me. Thanks everyone!

+1  A: 

the key to programming is looking for patterns, and then implementing them.

define your requirements:
• must have fixed-space fonts
• border at the top/bottom needs to be the length of text + margin (white space) + border
• text must have two spaces in all directions (vertical and horizontal)
• you want alternating periods and hyphens

def spaced(s):
    text = "hello"
    textLength = len(text)
    lineLength = textLength + 2 * (2 + 1)
    height = 5

    # at this point we know the first and fifth lines are the same and
    # we know the first and fourth are the same.  (reflected against the x-axis)

    hBorder = ""
    for c in range(lineLength):
        if c % 2:
            hBorder = hBorder + '.'
        else:
            hBorder = hBorder + '-'
    spacer = "." + " " * (lineLength - 2) + "."
    fancyText = "-  " + text + "  -"
    return (hBorder, spacer, fancyText, spacer, hBorder)

textTuple = spaced("hello world")
for line in textTuple:
    print line

Remember, you can only predict spacing for fixed width fonts. If you have any questions about the function above, ask in the comments. Cheers.

Devin
make sure if you enter this directly into the interpreter (on the command line), you'll need to insert the appropriate number of spaces as to not return prematurely from the function.
Devin
looks so complex.... :(
justin
@Devin: consider `hBorder = lineLength // 2 * "-." + "-"[:lineLength % 2]` instead of a laborious loop
John Machin