使用简单的代码在Java或Python上创建一个Hour Glass模式?
所以我想知道,是否有任何简单的代码可以使用Java或Python使用奇数或偶数输入制作一个小时玻璃图案?因为我的代码并不简单(我使用的是Python)
以下是输出示例:
然后,这是我的代码:
def evenGlassHour(target):
jsp=1
jtop=target
jbot=2
jbotspace=int(target/2)
eventarget=int(target/2)
temp=""
for i in range(eventarget):
for j in range(i):
temp+=" "
for jsp in range(jtop):
temp+="@"
jtop-=2
temp+="\n"
for i in range(eventarget-1):
for j in range(jbotspace-2):
temp+=" "
for j in range(jbot+2):
temp+="@"
jbot+=2
jbotspace-=1
temp+="\n"
print(temp)
def oddGlassHour(target):
jsp=1
jtop=target
jbot=1
jbotspace=int(target/2)
oddtarget=int(target/2)
temp=""
for i in range(oddtarget):
for j in range(i):
temp+=" "
for jsp in range(jtop):
temp+="@"
jtop-=2
temp+="\n"
for i in range(oddtarget+1):
for j in range(jbotspace):
temp+=" "
for j in range(jbot):
temp+="@"
jbot+=2
jbotspace-=1
temp+="\n"
print(temp)
target=int(input("Input : "))
if(target%2==0):
evenGlassHour(target)
else:
oddGlassHour(target)
这是我代码的结果:
Input : 6
@@@@@@
@@@@
@@
@@@@
@@@@@@
Input : 7
@@@@@@@
@@@@@
@@@
@
@@@
@@@@@
@@@@@@@
# 1 楼答案
在java中,您可以编写如下内容:
# 2 楼答案
在Python中,您可以利用这样一个事实,即可以将字符串乘以x,并将字符串与自身连接x次,如:
此外,您还可以对沙漏的顶部和底部使用相同的函数,方法是对
range
使用不同的值:编辑:您甚至可以删除递归调用,只需将两个范围^{} 放在一起,使函数更小:
最后,您可以使函数接受要打印的所需符号(任意长度),如下所示:
您还可以将这两个功能结合起来,使其更加荒谬:
# 3 楼答案
可以将字符串格式与
str.zfill
和递归一起使用:输出:
# 4 楼答案
使用中心调整字符串格式
灵感:https://stackoverflow.com/a/44781576
输出: