You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯迭代实现嵌套金字塔:代码输出不符预期求助

Fixing Your Nested Pyramid Iterative Implementation

Let's break down what was going wrong with your original code: it was printing a full single pyramid h times in a row, which is why you saw three identical pyramids stacked vertically for h=3. What we actually need is to print groups of pyramids, where each group has an increasing odd number of side-by-side pyramids (1, 3, 5... up to 2h-1), and each group contains h rows matching the rows of a single pyramid of height h.

Here's the corrected iterative implementation, sticking strictly to your requirement of no arrays or string manipulation beyond single-character prints:

def print_triangles(h):
    # Iterate over each group (1 to h groups total)
    for group in range(1, h + 1):
        num_pyramids = 2 * group - 1  # Number of side-by-side pyramids in this group
        # Iterate over each row of the single pyramid pattern
        for row in range(1, h + 1):
            stars_per_row = 2 * row - 1
            # Print each pyramid's current row
            for idx in range(num_pyramids):
                # Print the stars for this pyramid row
                for _ in range(stars_per_row):
                    print("*", end="")
                # Add a space separator only if it's not the last pyramid AND not the base row of the pyramid
                if idx != num_pyramids - 1 and row != h:
                    print(" ", end="")
            # Move to the next line after finishing the row
            print()

h = int(input())
print_triangles(h)

How This Works:

  1. Group Loop: We loop through h groups. Each group group uses 2*group -1 pyramids (so group 1 has 1 pyramid, group 2 has 3, group 3 has 5 for h=3).
  2. Row Loop: For each group, we loop through the h rows of a single pyramid.
  3. Pyramid Print Loop: For each row, we print the required number of side-by-side pyramid rows:
    • Print the correct number of stars for the current pyramid row.
    • Add a space between pyramids only when we're not on the last pyramid in the row, and we're not printing the base row of the pyramid (where pyramids should connect without spaces).

Test with h=3:

This code will output exactly what you expected:

*
***
*****
* * *
*** *** ***
***************
* * * * *
*** *** *** *** ***
*************************

内容的提问来源于stack exchange,提问作者user14679117

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:54:08