Reputation: 35
I'm beginner in Python. I am having difficulty resolving my problem:
Using nested for loops, print a right triangle of the character T
on
the screen where the triangle is one character wide at its narrowest point and seven characters wide at its widest point:
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
and
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Any idea?
Upvotes: 0
Views: 1002
Reputation: 1454
I hope you already have got the answer :)
Pattern # 1
def triangle(n):
for i in range(1, n +1):
print ('T' * i).rjust(n, ' ')
triangle(7)
##Results >>>
T
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Pattern # 2
def triangle1(n):
for i in range(1, n +1):
print ('T' * i)
triangle1(7)
# Results >>>>
T
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Pattern generation by using only for loops
Here I have tried to generate the with the help of only for loops and will very generalized way. Purposefully I have not used any readily available functions so you can always optimize it further.
Pattern # 1
def triangle(n):
# Iterate through number of columns
for i in range(1, n +1):
s = ""
# Iterate through number of rows
for j in list(range(i)):
s += "T"
print s
triangle(7)
Pattern # 2
def triangle1(n):
# Iterate through number of columns
for i in range(1, n +1):
s = ""
# Iterate through number of rows
for j in list(range(i)):
blank = ""
# Generate 'blank spaces'
for k in (range(n - i)):
blank += " "
# Generate 'T'
s += "T"
print blank + s
triangle1(7)
Upvotes: 1
Reputation: 897
I won't write a code for you but I can give you some hints:
Upvotes: 5