CS50 Mario双金字塔程序输出多余空格问题排查
双金字塔程序的空格问题
我需要实现一个可指定高度的双金字塔程序,两组金字塔间用两个空格分隔。以高度4为例,期望输出格式如下:
# # ## ## ### ### #### ####
我编写了对应Python代码,运行后输出看似符合预期,但无法通过check50检测,提示存在多余空格却无法定位问题。代码及检测结果如下:
def get_int(prompt): while True: try: value = int(input(prompt)) if 1 <= value <= 8: return value except ValueError: pass def main(): height = get_int("Height: ") for row in range(height): spaces = height - row - 1 hashes = row + 1 print(" " * spaces, "#" * hashes, end="") print(" ", end="") print("#" * hashes, " " * spaces) main()
检测显示高度为1、2、8时均不符合预期,比如高度1时预期输出# #,实际输出# #(前后多了空格)。
问题根源
你的代码使用print多参数输出时,默认会在参数之间自动添加空格。比如print(" " * spaces, "#" * hashes, end="")中,空格字符串和哈希字符串之间被自动加了一个空格,导致左侧金字塔前多了不必要的空格;最后一行print("#" * hashes, " " * spaces)不仅会在哈希和空格间加空格,还会在行尾输出多余空格。
修复后的代码
将所有字符串部分直接拼接成一个整体,避免print自动添加空格:
def get_int(prompt): while True: try: value = int(input(prompt)) if 1 <= value <= 8: return value except ValueError: pass def main(): height = get_int("Height: ") for row in range(height): spaces = height - row - 1 hashes = row + 1 line = " " * spaces + "#" * hashes + " " + "#" * hashes print(line) main()
解释
- 直接拼接所有元素:左侧空格 + 左侧哈希 + 两个分隔空格 + 右侧哈希,没有多余的末尾空格,每行结尾刚好是右侧哈希的最后一个字符,完全符合check50的格式要求。
- 以高度1为例,拼接后的字符串为
"" + "#" + " " + "#",即# #,与预期输出完全一致。
内容的提问来源于stack exchange,提问作者Kartick Narayan
相关产品推荐
相关产品推荐

