Ailen Samson Laguda - 1 year ago 114
Python Question

# Hollow Diamond in python

My goal is to create a hollow diamond using python.

Sample input:

``````Input an odd Integer:
9
``````

Sample output:

``````    *
* *
*   *
*     *
*       *
*     *
*   *
* *
*
``````

But so far, I have the following code that is not working right. Please help me to modify the code to achieve the goal above:

``````a=int(input("Input an odd integer: "))

k=1
c=1

r=a

while k<=r:
while c<=r:
print "*"
c+=1

r-=1
c=1

while c<=2*k-1:
print "*"
c+=1

print "\n"
k+=1

r=1
k=1
c=1

while k<=a-1:
while c<=r:
print " "
c+=1

r+=1
c=1

while c<= 2*(a-k)-1:
print ("*")
c+=1

print "\n"
k+=1
``````

The code above return a result that is very far from my goal.

``````Input an odd integer: 7
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*

*
*
*
*
*
*
*

*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*

*
*
*
*
*

*
*
*

*
``````

I am actually converting the code from this post: http://www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern written in C language and will modify later for the hollow one but I can't get it... There is something wrong with my conversion..

Your problem is that you keep using `print`. The print statement (and the function in Python 3) will add a line-break after what you printed, unless you explicitely tell it not to. You can do that in Python 2 like this:

``````print '*', # note the trailing comma
``````

Or in Python 3 (with the print function) like this:

``````print('*', end='')
``````

### My solution

I took my own take at the problem and came up with this solution:

``````# The diamond size
l = 9

# Initialize first row; this will create a list with a
# single element, the first row containing a single star
rows = ['*']

# Add half of the rows; we loop over the odd numbers from
# 1 to l, and then append a star followed by `i` spaces and
# again a star. Note that range will not include `l` itself.
for i in range(1, l, 2):
rows.append('*' + ' ' * i + '*')

# Mirror the rows and append; we get all but the last row
# (the middle row) from the list, and inverse it (using
# `[::-1]`) and add that to the original list. Now we have
# all the rows we need. Print it to see what's inside.
rows += rows[:-1][::-1]

# center-align each row, and join them
# We first define a function that does nothing else than
# centering whatever it gets to `l` characters. This will
# add the spaces we need around the stars
align = lambda x: ('{:^%s}' % l).format(x)

# And then we apply that function to all rows using `map`
# and then join the rows by a line break.
diamond = '\n'.join(map(align, rows))

# and print
print(diamond)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download