所以我想知道,是否有任何简单的代码可以使用Java或Python制作奇数或偶数输入的Hour Glass模式?因为我的代码不简单(我使用的是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)
Run Code Online (Sandbox Code Playgroud)
这是我的代码的结果:
Input : 6
@@@@@@
@@@@
@@
@@@@
@@@@@@
Input : 7
@@@@@@@
@@@@@
@@@
@
@@@
@@@@@
@@@@@@@
Run Code Online (Sandbox Code Playgroud)
您可以使用字符串格式化str.zfill和递归:
def _glass(_input, _original, flag=True):
if _input in {1, 2}:
return ('00' if _input == 2 else '0').center(_original) if flag else ''
if flag:
return ('0'*(_input)).center(_original)+'\n'+_glass(_input-2, _original, flag=flag)
return _glass(_input-2, _original, flag=flag)+'\n'+('0'*(_input)).center(_original)
def print_glasses(_input):
print(_glass(_input, _input)+_glass(_input, _input, False))
Run Code Online (Sandbox Code Playgroud)
for i in range(3, 8):
print_glasses(i)
print('-'*20)
Run Code Online (Sandbox Code Playgroud)
输出:
000
0
000
--------------------
0000
00
0000
--------------------
00000
000
0
000
00000
--------------------
000000
0000
00
0000
000000
--------------------
0000000
00000
000
0
000
00000
0000000
--------------------
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
570 次 |
| 最近记录: |