Suraj P Patil - 9 months ago 41

Python Question

I'm trying to print this pattern in Python:

`* *`

* *

* *

*

* *

* *

* *

And came up with this code:

`size = 7`

inner_size = size - 3

space=0

for i in range(inner_size):

print (' ' * space + '*' + ' ' * inner_size + '*')

inner_size -=2

space +=1

print " *"

t_size=7

t_inner_size = 0

space=3

for i in range(inner_size):

print (' ' * space + '*' + ' ' * inner_size + '*')

inner_size +=2

space -=1

But, it prints this :

`* *`

* *

**

**

*

How to print the required pattern?

Is it possible to do this in one loop?

Answer

I have used ideas from your existing code in the question and made a few tweaks to do it in a single loop with simple, crystal clear code:

```
def xprint(size):
i,j = 0,size - 1
while j >= 0 and i < size:
initial_spaces = ' '*min(i,j)
middle_spaces = ' '*(abs(i - j) - 1)
final_spaces = ' '*(size - 1 - max(i,j))
if j == i:
print initial_spaces + '*' + final_spaces
else:
print initial_spaces + '*' + middle_spaces + '*' + final_spaces
i += 1
j -= 1
xprint(7)
```

It prints out:

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

A linear-time straightforward way of doing it.