python

Hollow Diamond in Python with recursion


I've been trying to make a diamond out of forward and backwards slashes, so far I have this piece of code:

def upper_diamond(level,length):
if level <=length:
    print(" " * (length - level), end="")
    print("/", end="")
    print(" " * 2 * (level-1), end=" ")
    print("\\")
    upper_diamond(level + 1,length)

def lower_diamond(level,length):


def diamond(length):
    upper_diamond(1,length)

diamond(4)

and when I print it comes out as such:

   / \
  /   \
 /     \
/       \

I want to make a complete diamond and making the bottom part is stumping me, how do I make the bottom half print with the rest of the diamond?


Solution

  • Basing off your code, you can replicate the same behavior adjusting the offsets (changed end after spacing section to empty string to avoid opened edges):

    def upper_diamond (level, length):
        if level <= length:
            print(' ' * (length - level), end='')
            print('/', end='')
            print(' ' * 2 * (level - 1), end='')
            print('\\')
            upper_diamond(level + 1, length)
    
    def lower_diamond (level, length):
        if level <= length:
            print(' ' * (level - 1), end='')
            print('\\', end='')
            print(' ' * 2 * (length - level), end='')
            print('/')
            lower_diamond(level + 1, length)
    
    def diamond(length):
        upper_diamond(1, length)
        lower_diamond(1, length)
    
    diamond(4)
    

    Outputs:

       /\
      /  \
     /    \
    /      \
    \      /
     \    /
      \  /
       \/