Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

This question already has an answer here:

the contest is already finished, so I don't think it's cheating to ask: I am trying to optimize this small contest: pascal triangle I started with 4.72 and worked myself up to 7.48. The best made a 9.05 but in perl, python2 best score is 8.25. Unfortunately they don't let you look at what others did. My current solution is the following:

l=[1]
print 1
while(len(l)<31):
 print' '.join(map(str,l+[1]))
 l=[1]+map(lambda x,y:x+y,l,l[1:]+[1])

Now I tried to get rid of the loop in using list comprehension, but I am too new to python to get this done. Can anyone give me a hint for nested list comprehension shortening this code further down?

Thank you for your audience.

share|improve this question
In the list of answers to Generate Pascal's triangle you may find additional ideas. – Howard Mar 20 at 13:51
The shortest solution I know of is 68 bytes, which would have scored a 8.3. But apparently a 63 byte solution exists. – primo Mar 20 at 13:51
There's a 63-byte Python solution in the duplicate thread, but that's taking input from stdin, so hard-coding 31 would save 5 for a score of 8.55. – Peter Taylor Mar 20 at 13:53
@PeterTaylor The only problem with that solution, is that you'd need to replace print x with print' '.join(map(str,x)) for a loss of 18 bytes. – primo Mar 20 at 13:57
3  
Interesting. I must have posted that before I registered. That could have been made a byte shorter, actually: a=[];exec"a=map(sum,zip(a,[0]+a))+[1];print a;"*input() – primo Mar 20 at 14:28
show 2 more comments

marked as duplicate by Peter Taylor, M42, grc, beary605, dmckee Mar 29 at 5:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

This is a bit shorter, but still no good:

l=[1]
while(len(l)<32):
 print' '.join(map(str,l))
 l=[1]+map(int.__add__,l,l[1:]+[0])

And this one comes in at a score of 8.28 (credit to @primo):

l=[1];exec"print' '.join(map(str,l));l=map(sum,zip([0]+l,l+[0]));"*31
share|improve this answer
1  
Thank you, I learned a lot. Replacing the loop with a exec"..;"*count will server for future challenges. Also I like your int.__add__ in replacement of lambda x,y:x+y – Johannes Frank Mar 20 at 21:19
I like to say sorry not looking at the duplicate thread. I posted this one at stackoverflow and they recomended this site. So I posted it again, but forgot to do a thorough search. Thank you for your answers. – Johannes Frank Mar 20 at 21:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.