您是否在每行的开头打印一个附加字符? - 主要错误左对齐金字塔

发布于 2025-01-12 06:44:00 字数 537 浏览 1 评论 0原文

我目前在 cs50 的 pset6,mario-less。我的代码根据问题要求编译并打印左对齐金字塔,但是当我执行 check50 时,大多数代码都会失败。问题是什么?

from cs50 import get_int

# Ask user for input
n = get_int("Height: ")

# While loop to check condition
while n < 1 or n > 8:
    print("Invalid number ")
    n = get_int("Enter another number: ")

# One for loop to prin left sided piramid
for j in range(1, n + 1):
    spaces = n - j + 1
    print(" " * spaces + "#" * j)

I'm currently at pset6 from cs50, mario-less. My code compiles and prints the left aligned pyramid as the problem asks, but when I do a check50, most of them fail. What is the problem?

from cs50 import get_int

# Ask user for input
n = get_int("Height: ")

# While loop to check condition
while n < 1 or n > 8:
    print("Invalid number ")
    n = get_int("Enter another number: ")

# One for loop to prin left sided piramid
for j in range(1, n + 1):
    spaces = n - j + 1
    print(" " * spaces + "#" * j)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浴红衣 2025-01-19 06:44:00

我不久前做了 cs50,我的答案和你的类似(我们可能基于我们之前做的 C 代码)。但现在想一想,在 fstrings 的帮助下执行此操作的另一种方法是这样的:

n = int(input('height: ')
c = 1
for i in range(n):
    print(f'{" "*(n-1)}{"#"*c}')
    n -= 1
    c += 1

I did cs50 a while ago and my answer was something like yours (we probably based it on the C code we did prior). But thinking about it now, another way to do this with the help of fstrings would be like this:

n = int(input('height: ')
c = 1
for i in range(n):
    print(f'{" "*(n-1)}{"#"*c}')
    n -= 1
    c += 1
只是偏爱你 2025-01-19 06:44:00

按照目前的情况,对于 n == 5 您的代码将打印:

     #
    ##
   ###
  ####
 #####

但是,我们希望避免在每行开头出现额外的空格并得到:

    #
   ##
  ###
 ####
#####

因此只需减少要添加的空格数通过 1:

# One for loop to print left sided pyramid
for j in range(1, n + 1):
    spaces = n - j
    print(" " * spaces + "#" * j)

As it currently stands, for n == 5 your code will print:

     #
    ##
   ###
  ####
 #####

However, we want to avoid that extra space at the start of every line and get:

    #
   ##
  ###
 ####
#####

So just reduce the number of spaces you are adding by 1:

# One for loop to print left sided pyramid
for j in range(1, n + 1):
    spaces = n - j
    print(" " * spaces + "#" * j)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文