3

我的目标是使用 python 创建一个空心钻石。

样本输入:

Input an odd Integer:
      9

样本输出:

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

但到目前为止,我的以下代码无法正常工作。请帮我修改代码以实现上述目标:

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

上面的代码返回的结果与我的目标相差甚远。

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


*
*
*
*
*
*
*
*


*
*
*
*
*
*
*


*
*
*
*
*
*
*



*
*
*
*
*
*
*
*
*
*
*


*
*
*
*
*
*
*
*
*


*
*
*
*
*
* 
*


*
*
*
*
*


*
*
*





*

我实际上正在转换这篇文章中的代码:http: //www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern 用 C 语言编写,稍后将修改为空心的,但我可以'不明白...我的转换有问题..

4

9 回答 9

10

A Hollow diamond is the solution to the equation

|x|+|y| = N

on an integer grid. So Hollow diamond as a 1-liner:

In [22]: N = 9//2; print('\n'.join([''.join([('*' if abs(x)+abs(y) == N else ' ') for x in range(-N, N+1)]) for y in range(-N, N+1)]))
    *    
   * *   
  *   *  
 *     * 
*       *
 *     * 
  *   *  
   * *   
    *    
于 2013-01-02T13:47:02.353 回答
8

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)
于 2013-01-02T13:24:07.690 回答
1
def diamond(n, c='*'):
    for i in range(n):
        spc = i * 2 - 1
        if spc >= n - 1:
            spc = n - spc % n - 4
        if spc < 1:
            print(c.center(n))
        else:
            print((c + spc * ' ' + c).center(n))

if __name__ == '__main__':
    diamond(int(input("Input an odd integer: ")))
于 2013-01-02T13:31:23.770 回答
1

this is not pretty, but its a function that does what you want:

def make_diamond(size):
    if not size%2:
        raise ValueError('odd number required')
    r = [' ' * space + '*' + ' ' * (size-2-(space*2)) + '*' + ' ' * space for space in xrange((size-1)/2)]    
    r.append(' ' * ((size-1)/2) + '*' + ' ' * ((size-1)/2))
    return '\n'.join(r[-1:0:-1] + r)
  • first i check to make sure its an odd number,
  • then i create a list of the lines from the center downwards.
  • then i create the last point.
  • then i return them as as a string, with a mirror of the bottom on top without the center line.

output:

>>> print make_diamond(5)
  *  
 * * 
*   *
 * * 
  *  
>>> print make_diamond(9)
    *    
   * *   
  *   *  
 *     * 
*       *
 *     * 
  *   *  
   * *   
    *   
于 2013-01-02T13:32:29.827 回答
0

Made it in one single loop ;)

x = input("enter no of odd lines : ") #e.g. x=5
i = int(math.fabs(x/2)) # i=2 (loop for spaces before first star)
j = int(x-2) #j=3 # y & j carry loops for spaces in between
y = int(x-3) #y=2 
print ( " " * i + "*" )
i = i-1 #i=1

while math.fabs(i) <= math.fabs((x/2)-1): # i <= 1
      b = int(j- math.fabs(y)) # b = (1, 3, 1) no of spaces in between stars
      a = int(math.fabs(i)) # a = (1, 0, 1) no of spaces before first star
      print (" "* a + "*" + " "*b + "*")
      y = y-2 # 2,0,-2
      i = i-1 # 1,0,-1, -2 (loop wont run for -2)

i = int(math.fabs(i)) # i = -2
print ( " " * i + "*")
于 2015-08-04T21:42:48.883 回答
0

The previous answer has got two corrections, which've been done here :

import math
x = int(input("enter no of odd lines : ")) #e.g. x=5
i = int(math.fabs(x/2)) # i=2 (loop for spaces before first star)
j = int(x-2) #j=3 # y & j carry loops for spaces in between
y = int(x-3) #y=2 
print ( " " * i + "*" )
i = i-1 #i=1

while math.fabs(i) <= math.fabs((x/2)-1): # i <= 1
    b = int(j- math.fabs(y)) # b = (1, 3, 1) no of spaces in between stars
    a = int(math.fabs(i)) # a = (1, 0, 1) no of spaces before first star
    print (" "* a + "*" + " "*b + "*")
    y = y-2 # 2,0,-2
    i = i-1 # 1,0,-1, -2 (loop wont run for -2)

i = int(math.fabs(i)) # i = -2
print ( " " * i + "*")

Note : Now this works for both python 2.5x and python 3.x If you wish to know the difference in the two answers, then google it!

于 2016-11-25T10:57:55.853 回答
0
sizeChoice = 13
N = sizeChoice//2
for column in range (-N, N + 1):
    for row in range (-N, N + 1):
        if abs(column) + abs(row) == N:
            print ("*", end = " ")
        else:
            print(" ", end = " ")
    print ( )
于 2020-04-12T21:46:01.453 回答
0

this code works perfectly to print a hollow diamond where you can set diagonal length upto user requirement

n=int(input('Enter Odd Diagonal length :'))-1
j=n-1
print(' '*(n)+'*')
for i in range(1, 2*n):
    if i>n:
        print(' '*(i-n)+'*'+' '*(2*j-1)+'*')
        j-=1
    else:
        print(' '*(n-i)+'*'+' '*(2*i-1)+'*')
if n>1:
    print(' '*n+'*')
于 2020-06-20T13:43:30.807 回答
0

Hallow Diamond in Python using only print function

for i in range(1,6):
    print(' '*(5-i) + '*'*1 + ' '*(i-1) + ' '*max((i-2),0) + '*'*(1%i) )

for j in range(4,0,-1):
    print(' '*(5-j) + '*'*1 + ' '*(j-1) + ' '*max((j-2),0) + '*'*(1%j) )
    
于 2020-06-25T07:56:29.517 回答