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:

print 1
 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.


marked as duplicate by Peter Taylor, Toto, grc, beary605, dmckee Mar 29 '13 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.

  • \$\begingroup\$ In the list of answers to Generate Pascal's triangle you may find additional ideas. \$\endgroup\$ – Howard Mar 20 '13 at 13:51
  • \$\begingroup\$ The shortest solution I know of is 68 bytes, which would have scored a 8.3. But apparently a 63 byte solution exists. \$\endgroup\$ – primo Mar 20 '13 at 13:51
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Mar 20 '13 at 13:53
  • \$\begingroup\$ @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. \$\endgroup\$ – primo Mar 20 '13 at 13:57
  • 3
    \$\begingroup\$ 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() \$\endgroup\$ – primo Mar 20 '13 at 14:28

This is a bit shorter, but still no good:

 print' '.join(map(str,l))

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
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – Johannes Maria Frank Mar 20 '13 at 21:19
  • \$\begingroup\$ 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. \$\endgroup\$ – Johannes Maria Frank Mar 20 '13 at 21:28

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