3

I am struggling to find an efficient way to convert these for loops to a working set of while loops. Any Suggestions? I am using 2.7

def printTTriangle(height):
 for row in range(1,height+1):
    # print row T's
    for col in range(1,row+1):
        print 'T', 
    print

Thank you all for your help!

3
  • 8
    why do you wants to convert into while? for are better than while Commented Sep 19, 2013 at 16:53
  • 1
    You can also use * on strings: print 'T' * 4 # TTTT Commented Sep 19, 2013 at 16:55
  • also you can use xrange instead of range, might be slightly more efficient Commented Sep 19, 2013 at 16:57

3 Answers 3

7

It's like this:

def printTTriangle(height):
    row = 1
    while row < height+1:
        col = 1
        while col < row+1:
            print 'T', 
            col += 1
        print
        row += 1

Here's how I did it. For example, let's convert this line:

for row in range(1, height+1):

First step: create an iteration variable and initialize it in the starting value of the range:

row = 1

Second step: transform the ending value of the range into the loop condition, and careful with the indexes:

while row < height+1:

Finally, don't forget to advance the loop incrementing the iteration variable:

row += 1

Putting it all together:

row = 1
while row < height+1:
    row += 1
Sign up to request clarification or add additional context in comments.

Comments

2

You can simplify it and just use one while loop:

def printTTriangle(height):
    row = 1
    while row <= height:
        print 'T '*row
        row += 1

AND if you are not obsessed with while loops, here is a one liner:

def printTTriangle(height):
    print "\n".join(['T '*row for row in range(1, height+1)])

Comments

1

You can get rid of the inner loop with string multiplication operator (*) :

def printTTriangle(height):
 j = 1
 while j <= height:
     print 'T' * j + '\n '
     j += 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.