-1

EDIT ** I can't multiply strings by an integer. Its for a homework and those were the instructions **

I need to do a triangle in python using for loops or while loops(mandatory). The final output should look like this.

T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTT
TTTT
TTT
TT
T

I already figure the firs part, that prints from the first line to the middle line, but i cant figure how to reverse my function.

def triangle(base):
    for length in range(base+1):
        for b in range(length):
            print("T",end="")
    print() 

What I tried to do was sustracting length like this.

def triangle(base):
for length in range(base+1):
    for b in range(length):
        print("T",end="")
    print()
for length in range(base):
    for b in range(length-1):
        print("T",end="")
print()

But only print this and I cant find the way to keep printing the "T" until it gets done:

T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTT
4

3 回答 3

0

您可以在单个列表理解中执行此操作:

t = 6
['T' * (n if n < t else 2*t-n) for n in range(1,2*t)]

将其转换为单个 for 循环很简单:

t = 6
for n in range(1,2*t):
    print('T'*(n if n < t else 2*t-n))

更正了问题的变化:

[''.join('T' for _ in range(n if n < t else 2*t-n)) for n in range(1,2*t)]
----
for n in range(1,2*t):
    print(''.join('T' for _ in range(n if n < t else 2*t-n))
于 2013-10-18T01:08:26.107 回答
0
def triangle(base):
    T=''
    for i in range(n):
        Ts = Ts + 'T'
        print Ts
    for i in range(n-1):
        Ts = Ts[1:]
        print Ts

>>> pt(6)
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTT
TTTT
TTT
TT
T
于 2013-10-18T01:10:49.013 回答
0

尝试以下

def triangle(base):
    for i in range(1,base+1):
        print(''.join('T' for o in range(i)))
    for i in reversed(range(1,base)  # note the lack of the +1 on base
        print(''.join('T' for o in range(i)))

例子

from shapes import triangle
triangle(3)
T
TT
TTT
TT
T
于 2013-10-18T01:12:58.973 回答