HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Printing octo-thorpes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thorpesprintingocto

Problem

Given a number, for example, \$6\$, this Python function should print hashes in the following format:

#
    ##
   ###
  ####
 #####
######


This is the function used to accomplish this:

def hash_print(number):
    for i in range(number):
        hashes='#' *(i+1)
        spaces=' '*(number -(i+1))
        print("%s%s") %(spaces,hashes)


Is there any way that this can be improved?

Solution

Python's str has justifying functions. The relevant one here would be rjust(). So we could just use that directly:

def hash_print(number):
    for i in range(number):
        hashes = '#' * (i+1)
        print hashes.rjust(number)


This is also \$O(n^2)\$ to build up hashes over time, so on the off chance that performance becomes a consideration, we could build it up as we go:

def hash_print(number):
    hashes = [' '] * number
    for i in range(number):
        hashes[number - i - 1] = '#'
        print ''.join(hashes)

Code Snippets

def hash_print(number):
    for i in range(number):
        hashes = '#' * (i+1)
        print hashes.rjust(number)
def hash_print(number):
    hashes = [' '] * number
    for i in range(number):
        hashes[number - i - 1] = '#'
        print ''.join(hashes)

Context

StackExchange Code Review Q#105292, answer score: 4

Revisions (0)

No revisions yet.