Search code examples
pythonpython-2.7textnewline

Printing X-type pattern in Python 2.7


I'm trying to print this pattern in Python:

    *............*
    .**........**
    ..***....***
    ...********
    ...********
    ..***....***
    .**........**
    *............*

And came up with this code that does the job:

for row in range(1,5):
    print "." * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
for row in range (0,4):
    print("." * (3-row)+ "*" *(4 -row) + row * 4 * "." +"*" *(4 -row))

My question: is it possible to do this without using two loops? BTW, this is not for homework, I'm just playing around with some exercises from "Think Like a Programmer" by V. Anton Spraul and implementing the solutions in Python rather than C++.

Thanks in advance.


Solution

  • Without changing anything else, you can just do the loop over two ranges:

    for row in range(1,5)+range(4,0,-1):
        print "." * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
    

    Since you can add lists together:

    In [8]: range(1,5)
    Out[8]: [1, 2, 3, 4]
    
    In [9]: range(4,0,-1)
    Out[9]: [4, 3, 2, 1]
    
    In [10]: range(1,5) + range(4,0,-1)
    Out[10]: [1, 2, 3, 4, 4, 3, 2, 1]
    

    By the way, you can get rid of the leading dots using spaces:

    for row in range(1,5)+range(4,0,-1):
        print " " * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
    
    *............*
     **........**
      ***....***
       ********
       ********
      ***....***
     **........**
    *............*
    

    A more elegant thing to do might be to build a list of strings:

    X = []
    for row in range(1,5):
        X.append(" " * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*")
    

    Now, add the bottom half by just duplicating the top half in reverse:

    X = X + list(reversed(X))
    

    But when we print it we see a list:

    print X
    #['*............*', ' **........**', '  ***....***', '   ********', '   ********', '  ***....***', ' **........**', '*............*']
    

    So we can join them together with newlines:

    print '\n'.join(X)
    
    *............*
     **........**
      ***....***
       ********
       ********
      ***....***
     **........**
    *............*