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:
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]
CodePudding user response:
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]