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

如何用Python生成先递增至中间再递减的对称数字图案?

Fixing the Symmetric Number Pattern in Python

Got it, let's sort out this pattern problem for you! The key issue with your current code is that it only generates the increasing half of the symmetric pattern—you're missing the decreasing part after reaching the middle line.

What You Need vs. What Your Code Does

Your requirement is a symmetric "hill" pattern:

  • For n=5: 1 → 121 → 12321 → 121 → 1 (5 lines total)
  • For n=7: 1 → 121 → 12321 → 1234321 → 12321 → 121 → 1 (7 lines total)

Your current code generates a full pyramid that keeps growing until the last line, which isn't what you want.

Correct Code Implementation (Line-by-Line Output)

This version will print each segment on its own line, matching the symmetric hill shape:

# Reading number of lines
row = int(input('Enter how many lines? '))

# Generating the symmetric pattern
for i in range(1, row + 1):
    # Calculate the peak number for the current line
    # For first half: peak = i; for second half: peak = row - i + 1
    peak = min(i, row - i + 1)
    
    # Print increasing sequence from 1 to peak
    for j in range(1, peak + 1):
        print(j, end='')
    
    # Print decreasing sequence from peak-1 down to 1
    for j in range(peak - 1, 0, -1):
        print(j, end='')
    
    # Move to next line
    print()

How It Works

  • Peak Calculation: The peak variable uses min(i, row - i + 1) to determine the largest number in each line. For the first half of the pattern, the peak increases with each line; for the second half, it decreases back to 1.
  • Increasing/Decreasing Sequences: We first print numbers from 1 up to the peak, then print numbers from peak-1 down to 1 to form the symmetric string.

Alternative: Single Line with Spaces (Matching Your Example Format)

If you want all segments printed on a single line separated by spaces (like your example 1 121 12321 121 1), use this version:

row = int(input('Enter how many lines? '))
pattern_segments = []

for i in range(1, row + 1):
    peak = min(i, row - i + 1)
    # Build the segment string
    increasing = ''.join(str(j) for j in range(1, peak + 1))
    decreasing = ''.join(str(j) for j in range(peak - 1, 0, -1))
    segment = increasing + decreasing
    pattern_segments.append(segment)

# Print all segments separated by spaces
print(' '.join(pattern_segments))

Testing

  • For n=5, the line-by-line code will output:
    1
    121
    12321
    121
    1
    
  • The single-line version will output: 1 121 12321 121 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:32:42