pythonpadding

Print diamond knowing length and width


I need to print a diamond using Python by entering the length. I can already check whether the width is odd or even and make sure the inputted number is correct. However, my printed resulted is aligned to the left. For example, here's my output with width 10:

*
***
*****
*******
*********
*********
*******
*****
***
*
length = 10   #This line don't exist normally, its just to avoid the input and every check.
lengthTest = length
answer = lengthTest % 2
if (answer == 0):
    length_1 = 1
    while (length_1 < length):
        print("*" * length_1)
        length_1 = length_1 + 2
    length_1 = length_1 - 2
    while (length_1 > 0):
        print("*" * length_1)
        length_1 = length_1 - 2
        
else:
    print("odd")

Any solution to the space problem to make its actually look like a diamond?


Solution

  • Why bother with multiple for loops?

    for i in range(-n + 1, n):
        print('{:^{}}'.format('*' * ((n - abs(i)) * 2 - 1), n * 2 - 1))
    

    Here is the math:

    Every time we get +2 asterisks, and we want them rising until we hit the center and descending afterwards, so we iterate from -n+1 to n-1 and calculate the number of the asterisks by n minus the absolute current index (to provide reverse symmetry between [-n, -1] and [1, n]) multiplied by two, minus one to create a center-able diamond (odd lengths).

    We center it with string formatting using ^{} with n * 2 - 1, because that is the highest possible width (when i = 0, (n - abs(i)) * 2 - 1 would be n * 2 - 1).

    Outputs (for n = 5):

        *    
       ***   
      *****  
     ******* 
    *********
     ******* 
      *****  
       ***   
        *