Python空心钻石
发布时间:2020-12-20 12:40:31 所属栏目:Python 来源:网络整理
导读:我的目标是使用 python创建一个空心钻石. 样本输入: Input an odd Integer: 9 样本输出: * * * * * * ** * * * * * * * * 但到目前为止,我有以下代码无法正常工作.请帮我修改代码以实现上述目标: a=int(input("Input an odd integer: "))k=1c=1r=awhile k
我的目标是使用
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语言编写,稍后将修改为空心的但我无法得到它…我的转换有问题.. 解决方法
你的问题是你继续使用打印. print语句(以及Python 3中的函数)将在您打印的内容后添加换行符,除非您明确告诉它不要.你可以在Python 2中这样做:
print '*',# note the trailing comma 或者在Python 3中(使用print函数),如下所示: print('*',end='') 我的解决方案 我对问题采取了自己的看法并提出了这个解决方案: # 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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |