Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turning a list comprehension into a for loop

I ma trying to tunr the list comprehension codes trow=[left+right for left,right in zip(trow+y, y+trow)] into a for loop instead of a list comprehension. I have attempted to do this conversion but it does not work. How will I be able to do this?

For loop Code:

def PascalTriangle(n):
   trow = [1]
   y = [0]
   for x in range(n):
      print(trow)
      for left,right in zip(trow+y, y+trow):
        trow.append(left+right)
   return n>=1

PascalTriangle(6)

List comprehension Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def PascalTriangle(n):
   trow = [1]
   y = [0]
   for x in range(n):
      print(trow)
      trow=[left+right for left,right in zip(trow+y, y+trow)]
   return n>=1

PascalTriangle(6)

Output:

[1]
[1, 1, 1]
[1, 1, 1, 1, 2, 2, 1]
[1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 3, 4, 3, 1]
[1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 3, 4, 3, 1, 1, 2, 2, 2, 3, 4, 3, 2, 3, 4, 4, 5, 7, 7, 4, 1]
[1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 3, 4, 3, 1, 1, 2, 2, 2, 3, 4, 3, 2, 3, 4, 4, 5, 7, 7, 4, 1, 1, 2, 2, 2, 3, 4, 3, 2, 3, 4, 4, 5, 7, 7, 4, 2, 3, 4, 4, 5, 7, 7, 5, 5, 7, 8, 9, 12, 14, 11, 5, 1]

Expected Output:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

>Solution :

You could use a temporary list to collect all values:

def PascalTriangle(n):
    trow = [1]
    y = [0]

    for x in range(n):
        print(trow)
        line = []
        for left, right in zip(trow + y, y + trow):
            line.append(left + right)
        trow = line
    return n >= 1


PascalTriangle(6)

Out:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading