如何在python中反转形状?

时间:2017-12-02 06:52:41

标签: python-3.x

我是猎人,我对即将到来的考试感兴趣。基本上我想知道是否有一种方法可以制作和塑造(在这种情况下为三角形)反转。

以下是我的代码。但我还有另一个代码。只是想知道是否有一种比刮擦和重写更简单的方法。

def a(b):
    num = 1
    count= 0

    for i in range(0, b):
        row = ''

        for k in range(0, b-i):
            row = row + '      '
        count=count+2

        for j in range(1, count):
            if (num <10):
                row = row+'     '+str(num)
            if (num>9 and num<99):
                row = row+'    '+str(num)
            if (num==99):
                row = row+' '
            if (num>=99 and num<=1000):
                row = row+'   '+str(num)
            if (num>=1001 and num<=10000000):
                row = row+'  '+str(num)
            num = num +1
        print '\r'
        print(row)

b= input(str("number of rows:  "))

a(b)


def a(number):
    ctr = 1
    while(ctr <= number):
        row_spaces= ' ' * (number - ctr)
        row = (2*ctr-1) * '$'
        print(row_spaces+row)
        ctr = ctr +1

number= input(str("what is the amount of rows?  "))
a(number)

2 个答案:

答案 0 :(得分:0)

要反转你的三角形,你需要反转你的逻辑空间。用下面的代码改变你的第二个while循环它应该工作,我只对你的代码做了一些修改:

def a(number):
    ctr = number
    while(ctr >= 1):
        row_spaces= ' ' * (number - ctr)
        row = (2*ctr-1) * '$'
        print(row_spaces+row)
        ctr = ctr -1

number= int(input("what is the amount of rows?  "))
a(number)

输出:

what is the amount of rows?  3
$$$$$
 $$$
  $

答案 1 :(得分:0)

def a(b):
b = int(b)
num = b*b -1
count = b*2

for i in range(0, b):
    row = ''

    for k in range(0, i):
        row = row + '      '

    num = num - (count-3)

    for j in range(1, count):
        if (num <10):
            row = row+'     '+str(num)
        if (num>9 and num<99):
            row = row+'    '+str(num)
        if (num==99):
            row = row+' '
        if (num>=99 and num<=1000):
            row = row+'   '+str(num)
        if (num>=1001 and num<=10000000):
            row = row+'  '+str(num)
        num = num +1

    num = num - 1 -(count)
    count = count-2

    print '\r'
    print(row)

b= input("number of rows:  ")
a(b)