[Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion)
Kent Johnson
kent37 at tds.net
Thu Oct 5 17:25:46 CEST 2006
Asrarahmed Kadri wrote:
> #Implementation of Pascal Triangle
>
> num_of_lines = input("How many lines you want to display")
>
> list1 = []
>
> for i in range(num_of_lines):
> flag = 0
> tmp = []
> for j in range(i+1):
> if flag == 0 or j == i:
> tmp.append(1) # for the first or teh last element of the line
> flag = 1
> else:
> tmp.append(list1[i-1][j-1]+list1[i-1][j]) # for rest, add
> teh numbers in previous row
>
> list1.append(tmp)
That's good. You could shorten it a little by getting rid of flag and
just testing for j==0 or j==i. Here is another way to do it, it requires
priming the output with the first row but the loop is a little shorter:
In [1]: binom = [[1]]
In [3]: for i in range(5):
...: prev = binom[i]
...: next = [1] + [ prev[j]+prev[j+1] for j in
range(len(prev)-1) ] + [1]
...: binom.append(next)
...:
...:
In [4]: binom
Out[4]: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5,
10, 10, 5, 1]]
There's a truly hideous one-liner hidden in your solution. It uses
nested list comprehensions, a hack to refer to the list being built
within a list comp, and the new conditional expression. Be careful who
you show this too, it may scare dogs and small children ;) It does
actually work:
list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j !=
0 and j != i) else 1 for j in range(i+1) ] for i in range(num_of_lines) ]
Now we know why conditional expressions were added to Python 2.5! See
this recipe for details about the locals() hack:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297
Sorry I couldn't resist :-)
Kent
More information about the Tutor
mailing list