【问题标题】:How do i print this design pattern我如何打印这个设计图案
【发布时间】:2023-02-23 13:23:05
【问题描述】:

我目前正在尝试在模式下编写代码......但无法思考需要如何为其定义逻辑。这是我第一次不知道如何开始

预期输出:

 1

 2 3

 4 5 6

 7 8 9 10

 11 12 13 14 15 

【问题讨论】:

  • 每行多少个数字?你打印的每个数字之间有什么关系?

标签: python


【解决方案1】:

您可以使用嵌套循环。我已经在代码的注释中解释了变量的含义

# Define the number of rows for the pattern 
#in your question it's 5, but I will test with 6
num_rows = 6

# Create a variable to keep track of the current number (in each row)
current_num = 1

# Loop over each row
for i in range(num_rows):
    # Loop over each number (column) in the current row
    for j in range(i + 1):
        # Print the current number and a space
        print(current_num, end=" ")

        # Increment the current number
        current_num += 1

    # Go to the next line after each row (new line)
    print()

   # 1 
   # 2 3 
   # 4 5 6 
   # 7 8 9 10 
   # 11 12 13 14 15 
   # 16 17 18 19 20 21 

【讨论】:

  • 除此之外,这似乎是一个相当常见的家庭作业问题,如果对其进行自动评分,最后额外的 " " 可能会导致它无法通过测试用例。在那种情况下,您可以进行字符串连接(即打印前的string += str(current_num) + " "string.trim())以达到类似的效果。
【解决方案2】:

您可以使用 for 循环来实现此目的。这是一个简单的函数,可以做你想做的;它需要一个参数来表示要打印多少行,例如,如果您将“行”设置为 5,它将打印 5 行,这就是您在帖子中显示的内容。

代码:

def printpattern(rows):
    num = 1
    for i in range(0, rows):
        for j in range(0, i+1):
            print(num, end=' ')
            num = num + 1
        print()

【讨论】:

    【解决方案3】:

    这叫做弗洛伊德三角,如果你想研究的话。这是一个简单的循环迭代。

    rows = int(input("num of rows: "))
    num = 1
    
    for i in range(1, rows+1):
        for j in range(1, i+1):
            print(num, end=' ')
            number += 1
        print()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2021-04-03
      相关资源
      最近更新 更多