• 打印三角型的练习


    编写函数,接受一个n,n为正整数,左右两种打印方式。要求数字必须对齐

    12 11 10 9 8 7 6 5 4 3 2 1
       11 10 9 8 7 6 5 4 3 2 1
          10 9 8 7 6 5 4 3 2 1
             9 8 7 6 5 4 3 2 1
               8 7 6 5 4 3 2 1
                 7 6 5 4 3 2 1
                   6 5 4 3 2 1
                     5 4 3 2 1
                       4 3 2 1
                         3 2 1
                           2 1
                             1
                             1
                           2 1
                         3 2 1
                       4 3 2 1
                     5 4 3 2 1
                   6 5 4 3 2 1
                 7 6 5 4 3 2 1
               8 7 6 5 4 3 2 1
             9 8 7 6 5 4 3 2 1
          10 9 8 7 6 5 4 3 2 1
       11 10 9 8 7 6 5 4 3 2 1
    12 11 10 9 8 7 6 5 4 3 2 1
    

    补空格法
    def trangle2(n):
        nums = [i for i in range(n,0,-1)]
        length = len(nums)
        
        for i in range(length):
            for j in range(length):
                if i<=j:
                    print('{:>{}}'.format(nums[j],len(str(nums[j]))+1),end='')
                else:
                    print('{}'.format(' '*(len(str(nums[j]))+1)),end='')
            print()
        for i in range(length):
            for j in range(length,0,-1):
                if i+1>=j:
                    print('{:>{}}'.format(nums[-j],len(str(nums[-j]))+1),end='')
                else:
                    print('{}'.format(' '*(len(str(nums[-j]))+1)),end='')
            print()

    靠右对齐法

    def trangle_print(n):
        nums = ' '.join(str(i) for i in range(n,0,-1))
        width = len(nums)
        start = -1
        step = 2
        points = {10**i for i in range(1,3)}
        for i in range(1,n+1):
            print('{:>{}}'.format(nums[start:],width))
            if i+1 in points:
                step += 1
            start = start -step

    字符串切割法

    def trangle1(n):
        nums = ' '.join([str(i) for i in range(n,0,-1)])
        length = len(nums)
        print(nums)
        for i in range(len(nums)):
            if nums[i] ==' ':
                print('{}{}'.format(' '*(i+1),nums[(i+1):]))
                
        for j in range(len(nums)-1,0,-1):
            if nums[j] == ' ':
                print('{}{}'.format(' '*(j),nums[j:]))
        print(nums)



































  • 相关阅读:
    git和TortoiseGit安装
    poi导出excel
    POI生成word文档
    java反编译工具
    如何把wecenter的推荐的问题模块单独调取出来?
    想学网站运营?我教你啊!(下)
    想学网站运营?我教你啊!(中)
    想学网站运营?我教你啊!(上)
    织梦模块管理里面空白
    Discuz/X3.1去掉标题中的Powered by Discuz!以及解决首页标题后的"-"
  • 原文地址:https://www.cnblogs.com/rprp789/p/9520190.html
Copyright © 2020-2023  润新知