我目前在解决此python模式问题方面有些困难,在这里我无法生成此问题所需的正确输出。如果我能从你们那里得到一些帮助或反馈,那就太好了!谢谢!!
def print_triangle(sentence):
if len(sentence) % 4 != 0:
return False
else:
char_list = list(sentence)
x = 0
n = int(len(sentence) / 4) + 1
for row in range(1,n+1):
for col in range(1,2*n):
if row ==n or row+col == n+1 or col-row == n-1:
print(char_list[x] ,end="")
x += 1
else:
print(end=" ")
print()
return True
如果调用了函数print_triangle('abcdefghijkl')
,它应该能够生成以下输出:
a
b l
c k
defghij
Return value:True
但是,这是我得到的输出
a
b c
d e
fghijkl
Return value:True
答案 0 :(得分:2)
算法:
def print_triangle(sentence):
n = len(sentence)
if n % 4 != 0:
return False
# special case handling ;)
elif n==4:
print(" " + sentence[0], sentence[1:], sep="\n")
return True
else:
numRows = n//4
for row in range(numRows+1): # amount of total triangle rows
# end case, print the rest thats not been printed
if row == numRows:
print(sentence[row:-row+1])
return True
# normal case: print enough spaces, then 1 letter, do not end the line
print(' '*(numRows - row)+sentence[row],end="")
# on all but the first line: print padding spaces and last letter
if row != 0:
print(' '*(2*row-1)+sentence[n-row])
else:
print("") # newline to "close" this line if on line 0
print("")
r = print_triangle(input())
print(r) # or do print("Return value: {}".format(r)) to be exact...
输出:({'abcdefghijkl'
)
a
b l
c k
defghij
True
输出:({'abcdefghijklmnop'
)
a
b p
c o
d n
efghijklm
True
输出:({'abc'
)
False