如何在不重复elif行的情况下增加多个层?无法使+= %1正常工作。或者是不同的字符串方法?我对Python当然是个新手。
layer = int(input("Give a number between 2 and 26: "))
table_size = layer + layer - 1
ts = table_size
center = (ts // 2)
for row in range(ts):
for col in range(ts):
if row == col == (center):
print("A", end="")
elif (row > center or col > center \
or row < center or col < center) \
and row < center + 2 and row > center - 2 \
and col < center + 2 and col > center - 2 :
print("B", end="")
elif (row > center+1 or col > center+1 \
or row < center-1 or col < center-1) \
and row < center+3 and row > center-3 \
and col < center+3 and col > center-3 :
print(chr(67), end="")
else:
print(" ", end="")
print()
CCCCC
CBBBC
CBABC
CBBBC
CCCCC发布于 2021-06-11 23:10:47
您可以求助于numpy来准备字母表的索引,然后使用准备好的索引来获得最终的字符串。这是如何实现的:
# Get your number of layers
N = int(input("Give a number between 2 and 26: "))
assert 2<=N<=26, 'Wrong number'
# INDEX PREPARATION WITH NP
import numpy as np
len_vec = np.arange(N)
horiz_vec = np.concatenate([np.flip(len_vec[1:]), len_vec])
rep_mat = np.tile(horiz_vec, [ 2*N-1, 1])
idx_mat = np.maximum(rep_mat, rep_mat.T)
# STRING CREATION: join elements in row with '', and rows with newline '\n'
from string import ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
final_string = '\n'.join(''.join([ascii_uppercase[i] for i in row]) for row in idx_mat)
# PRINTING THE STRING
print(final_string)使用N=3的示例
#> len_vec
array([0, 1, 2])
#> horiz_vec
array([2, 1, 0, 1, 2])
#> rep_mat
array([[2, 1, 0, 1, 2],
[2, 1, 0, 1, 2],
[2, 1, 0, 1, 2],
[2, 1, 0, 1, 2],
[2, 1, 0, 1, 2]])
#> idx_mat
array([[2, 2, 2, 2, 2],
[2, 1, 1, 1, 2],
[2, 1, 0, 1, 2],
[2, 1, 1, 1, 2],
[2, 2, 2, 2, 2]])
#> print(final_string)
CCCCC
CBBBC
CBABC
CBBBC
CCCCC发布于 2021-06-12 01:21:32
这是一个包含常规python列表的示例:
from string import ascii_uppercase
result = []
# Get your number of layers
N = int(input("Give a number between 2 and 26: "))
assert 2<=N<=26, 'Wrong number'
for i in range(N):
# update existing rows
for j, string in enumerate(result):
result[j] = ascii_uppercase[i] + string + ascii_uppercase[i]
# add top and bottom row
result.append((2*i+1)*ascii_uppercase[i])
if i != 0:
result.insert(0, (2*i+1)*ascii_uppercase[i])
# print result
for line in result:
print(line)发布于 2021-06-13 02:31:40
layer = int(input("Give a number between 2 and 26: "))
table_size = layer + layer - 1
ts = table_size
center = (ts // 2)
counter=0
print(center)
for row in range(ts):
for col in range(ts):
if row<=center and ts-counter>col:
outcome=65+center-min(row,col)
elif row <=center and col>=ts-counter :
outcome=65+col-center
elif row>center and ts-counter>col:
outcome=65+center-min(row,col)
elif row >center and col<counter :
outcome=65+row-center
elif row >center and col>=counter :
outcome=65+row-center+(col-counter)
print(chr(outcome), end="")
counter=counter+1
print()https://stackoverflow.com/questions/67938383
复制相似问题