【问题标题】:Drawing a square with "." and " " only in Python用“.”画一个正方形和 " " 仅在 Python 中
【发布时间】:2017-03-10 17:09:17
【问题描述】:

我正在尝试制作一个只有空格和点的正方形,但我遇到了问题。 我需要以这种方式编写代码,因此我可以在每个参数的 1 个输入中更改正方形的大小。我遇到了“sides”变量的问题,如何仅通过仅提供 1 个输入值来使左侧和右侧之间的空间自动化。

def square_shape(top,sides,bottom):
            top = ". "*top
            sides =((".")+("     .\n"))*sides
            bottom = ". "*bottom
            print top
            print sides,bottom
        square_shape(8,7,8)

P.S 使用此代码,它工作得非常好,但是当我更改 top 和 bottom 的大小时,不会在侧面创建所需的空间。 我希望我是清楚的。

提前谢谢你

【问题讨论】:

    标签: python size spaces


    【解决方案1】:

    使空间取决于正方形的长度,不要在字符串中使用\n,否则你的最后一行也会打印一个换行符 -

    def square_shape(leng): # no need to use 3 variables
            print (". "*leng)
            for _ in range(leng-2):
                print (". " + "  " * (leng - 2) + ".")
            print (". "*leng)
    square_shape(8)
    

    输出 -

    . . . . . . . . 
    .             .
    .             .
    .             .
    .             .
    .             .
    .             .
    . . . . . . . . 
    

    【讨论】:

    • 完美不过(.join)方法我还没学会,下周要期中,不知道用了会不会有问题.非常感谢您的宝贵时间!
    【解决方案2】:

    这个怎么样?

    def square_shape(size):
        print '. ' * size + '.'
        print ('.' + '  ' * (size-1) + ' .\n') * (size-1),
        print '. ' * size + '.'
    

    【讨论】:

    • @Bendik 这不会打印一个完美的正方形,在最后一行之前会有一个换行符。
    • 现在是一个完美的正方形,面积*大小,刚刚固定了行数。
    【解决方案3】:

    一点点优化!

    square_shape = int(input())
    print ("."*square_shape)
    for _ in range(square_shape-2):
        print ("."+ " "*(square_shape-2) + ".")
    print ("."*square_shape)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多