用于打印 n 行模式 1 121 12321 12 1 的 Python 程序

标签 python

这个问题在这里已经有了答案:





print a diamond of numbers in python

(3 个回答)


12 天前关闭。




当 n = 5 时,模式必须是:

    1
   121
  12321
   121
    1
到目前为止我尝试过的:
# Pattern 1-121-12321 pyramid pattern

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

# Generating pattern
for i in range(1,row+1):
    
    # for space
    for j in range(1, row+1-i):
        print(' ', end='')
    
    # for increasing pattern
    for j in range(1,i+1):
        print(j, end='')
    
    # for decreasing pattern 
    for j in range(i-1,0,-1):
        print(j, end='')
    
    # Moving to next line
    print()
我得到的输出:
    1
   121
  12321
 1234321
123454321
我知道类似这样的模式的逻辑:
    *
   ***
  *****
 *******
但是数字模式似乎令人困惑,我无法理解逻辑。
TL;博士
用于生成以下用于打印 n 行模式的 Python 程序:
例如。当 n=7 时:
   1
  121
 12321
1234321
 12321
  121
   1 

最佳答案

这段代码怎么样:

for i in range(n):
    temp = 0 # Store the value of the number to square (so 1, 11,...)
    if (i < n / 2):
        for j in range(i + 1):
            temp += 10 ** j # Construct the number (1 = 1, 11 = 1 + 10, 111 = 1 + 10 + 10 ^ 2,...)
        for _ in range(int(n / 2 - i)):
            print(' ', end = '') # Add space indentation
    else:
        for j in range(n - i): # Count in reverse now
            temp += 10 ** j # Construct the number (1 = 1, 11 = 1 + 10, 111 = 1 + 10 + 10 ^ 2,...)
        for _ in range(int(i - n / 2) + 1):
            print(' ', end = '') # Add space indentation
    print(temp ** 2) # Square the temporary value

(Fun mathematical fact: the string you print have a property of:
1 = 1 ^ 2; 121 = 11 ^ 2; 12321 = 111 ^ 2;...)

关于用于打印 n 行模式 1 121 12321 12 1 的 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69372285/

相关文章:

python - 为什么当我覆盖 base.html django-admin 时已禁用响应式界面?

python - LDA 生成的组件少于 Python 中要求的组件

python - 如何在 matplotlib python 中生成每年发生次数的条形图?

python - pip::找不到与 tensorflow-gpu 匹配的分布

python - python中的networkx用于删除节点

python - 使用 xlsxwriter 自动扩展行

python - 在空行上拆分 &lt;textarea&gt; 帖子

python - 导入错误 : No module named FileDialog - after PyInstaller

python - Statsmodel Z 测试未按预期工作(statsmodels.stats.weightstats.CompareMeans.ztest_ind)

python - 获取接口(interface)的最新全局 ipv6 地址