托伦,
函数中有几个小错误和一个逻辑问题print_y_to_a()
请注意,此函数生成一个以z开头的字符串,但您希望将字符串以相反的方向连接,而您的另一个函数print_a_to_y()确实停止了(+1位置)。例如:
^{pr2}$
还要注意,您需要添加新行字符“\n”以获得一些不错的输出。在
我的解决方案是:def print_a_to_y(lev):
palindrome=""
counter=0
for i in range (ord('a'),ord('z')):
if counter<=lev:
palindrome = palindrome+ chr(i)
counter+=1
else:
pass
return palindrome
def print_y_to_a(cut):
palindrome=""
for i in range (ord('z'),ord('a')-1, -1):
palindrome = palindrome + chr(i)
return palindrome[-cut:]
def palin (lev):
paal = print_a_to_y(lev) + print_y_to_a(lev)
return paal
def pyramid (levels=15):
res=""
for i in range (levels):
if i==0:
res=print_a_to_y(i)+"\n"
elif i>0:
res= res + str(palin(i)) + "\n"
else:
pass
return res
print pyramid()
另外,你需要在函数的末尾加上return语句,否则屏幕上会出现“None”。在
干杯,希望这有帮助。
维克多