Printing X-type pattern in Python 2.7 -
i'm trying print pattern in python:
*............* .**........** ..***....*** ...******** ...******** ..***....*** .**........** *............*
and came code job:
for row in range(1,5): print "." * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*" row in range (0,4): print("." * (3-row)+ "*" *(4 -row) + row * 4 * "." +"*" *(4 -row))
my question: possible without using 2 loops? btw, not homework, i'm playing around exercises "think programmer" v. anton spraul , implementing solutions in python rather c++.
thanks in advance.
without changing else, can loop on 2 ranges:
for row in range(1,5)+range(4,0,-1): print "." * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*"
since 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 way, can rid of 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 might build list of strings:
x = [] row in range(1,5): x.append(" " * (row -1) + row * "*" + (16 - row * 4) * "." + row * "*")
now, add bottom half duplicating top half in reverse:
x = x + list(reversed(x))
but when print see list:
print x #['*............*', ' **........**', ' ***....***', ' ********', ' ********', ' ***....***', ' **........**', '*............*']
so can join them newlines:
print '\n'.join(x) *............* **........** ***....*** ******** ******** ***....*** **........** *............*
Comments
Post a Comment