-1

I'm writing a code for homework, it needs t o output the values for pascal's triangle, but not in a triangle. for instance I input

pascalLine(2) 

it outputs:

[1,2,1] 

and for:

pascalLine(4) 

it outputs:

[1,4,6,4,1] 

I currently have this code and I believe it is far from complete, because It outputs a triangle.

def pascalLine(n): for rownum in range (n): newValue=1 PrintingList = list() for iteration in range (rownum): newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 ) PrintingList.append(int(newValue)) print(PrintingList) print() 
2
  • "it needs t o output the values for pascal's triangle, but not in a triangle" - I'm not really sure what your desired output is here. Commented Oct 22, 2012 at 0:25
  • @millimoose: I think the [1,2,1] and [1,4,6,4,1] the OP gives are examples of the desired output. I.e. the function should return the nth row of Pascal's triangle as a list. Commented Oct 22, 2012 at 0:26

3 Answers 3

3

Assuming your original code to calculate row n is correct, you can just get rid of the outer loop:

def pascalLine(n): newValue=1 row = [newValue] for i in range (n): newValue = (newValue * (n-i)) / ( i + 1 ) row.append(newValue) print(row) print() 
Sign up to request clarification or add additional context in comments.

Comments

3

You can just use this simple algorithm for computing an arbitrary row without having to compute the entire triangle:

def pascal_row(n): row = [1] for col in range(1, n): row.append(row[-1] * (n - col) / col) return row 

3 Comments

the solution doesn't give n-th row of the PT, rather gives (n-1)th row. by wikipedia definition, the 1st row is considered 0-th row.
@kmonsoor: The rows correspond to powers of (x + y). Since (x + y)^0 = 1, the 0th row will be 1.
@kmonsoor: Numberings in mathematics are somewhat arbitrary, so there's no "right" answer.
0

This gives [1] for row zero and [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1] for row 12:

 def getRow(r): row = [1] for c in range(1,r+1): row += [row[-1]*(r-c+1)//c] return row 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.