尝试在python中打印框架'*'和对角线 [英] Try to print frame '*' and diagonal in python

查看:108
本文介绍了尝试在python中打印框架'*'和对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在框架和对角线中打印'*'.

I try to print '*' in frame and in diagonal .

这就是我所做的:

x=10
y=10
def print_frame(n, m, c):
  print c * m
  for i in range(1, n - 1):
    print c ,' '*(n-2-i),c, ' '*i , c  , c
  print c * m

print_frame(10, 10, '*')

这是结果:

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

推荐答案

正如我在注释中所指定的,只有正方形矩阵具有对角线.但是即使如此,事情也比看起来复杂了一点.

As I specified in my comment, only square matrices have diagonals. But even for those, things are "a bit" more complex than they seem:

  • 我本可以在一个循环中完成此操作,但是我认为最好查看所有部分"
  • (字符串)计算本可以以更紧凑的方式编写,但是为了清楚起见,我将它们保留为原样
  • 还添加了递归变量.我更喜欢这一点,因为它很清楚(尽管通常来说,递归有局限性),尤其是由于给定问题的性质,递归的深度不足以生成 StackOverflow 或具有对性能产生负面影响
  • 我返回"它们而不是在函数内部打印字符串.这是一种优化技术:如果在多个地方都需要它们,则该函数只需调用一次即可.
  • 函数是生成器( yield 而不是 return ).这也是一种优化(这是 Python ic)
  • I could have done it in a single loop, but I think it's better to see all the "sections"
  • The (string) calculations could have been written in a more compact way, but I left them as they are for clarity
  • Also added the recursive variant. I prefer this one as it's clearer (although in general, recursion has limitations), especially since given the nature of the problem, the recursion doesn't go deep enough in order to generate StackOverflow, or to have a negative effect on performance
  • Instead of printing the string inside the function, I "return" them. That is an optimization technique: if they are needed in more than one place, the function only needs to be called once
  • The functions are generators (yield instead of return). That is also an optimization (and it's Pythonic)

code01.py :

#!/usr/bin/env python3

import sys


def square_frame_iterative(side, char="*"):
    yield char * side  # Upper row
    for i in range(1, side - 1):
        edge_space = min(i - 1, side - 2 - i)
        mid_space = side - 2 * edge_space - 4
        mid_text = char if mid_space < 0 else char + " " * mid_space + char
        yield char + " " * edge_space + mid_text + " " * edge_space + char
    yield char * side  # Lower row


# Recursion
def _square_frame_recursive(side, char, i):
    if i == side // 2 - 1:
        if side % 2 :
            yield char + " " * ((side - 3) // 2) + char + " " * ((side - 3) // 2) + char  # Mid row
    else:
        s = char + " " * i + char + " " * (side - 2 * i - 4) + char + " " * i + char
        yield s
        yield from _square_frame_recursive(side, char, i + 1)
        yield s


def square_frame_recursive(side, char="*"):
    yield char * side  # Upper row
    if side <= 1:
        return
    yield from _square_frame_recursive(side, char, 0)
    yield char * side  # Lower row

# Recursion end


def main(argv):
    dim = 10
    square_frame_func = square_frame_iterative
    if argv:
        if argv[0].isdigit():
            dim = int(argv[0])
        if (len(argv) > 1) and argv[1].lower().startswith("rec"):
            square_frame_func = square_frame_recursive
    frame_string = "\n".join(square_frame_func(dim))
    print(frame_string)


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    main(sys.argv[1:])
    print("\nDone.")

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055342983]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code01.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32

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

Done.

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055342983]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code01.py 7 rec
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32

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

Done.

这篇关于尝试在python中打印框架'*'和对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆