This code prints numbers in a triangled way, such as:


This is the code:

def triangled(num):
    num = str(num)
    pieces = [num[:i] for i in range(len(num))]
    return pieces + [num] + pieces[::-1]

def triangled_print(num):
    for i in triangled(num):


1 Answer 1


The code looks fine.

I have a few suggestions, but these are nitpicks rather than major problems:

  • Give your functions better names. I'd suggest triangle_lines and triangle_print, because triangled is just a bit ambiguous. Along the same lines, consider adding docstrings so that the user can more easily find out how your code works.

  • In the final line of triangled, I'd write it slightly differently:

    return pieces + [num] + list(reversed(pieces))

    There's nothing wrong with taking a reverse slice, but I think this makes it slightly clearer what's going on.

  • If you used this code on a really long number, you might start to have memory problems with the list returned from triangled(<bignum>). You could rewrite it to be a generator, but it's not essential if you're only going to be using this for small numbers.

  • Your triangle has a blank line at the top or bottom. That might be okay; if not, tweak the range to start at 1 instead of (implicit) 0:

    pieces = [num[:i] for i in range(1, len(num))]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.