# Let's Golf! [Challenge]

 9 6 As some of you know, code-golfing means taking a problem & coding it in a way that takes the fewest characters. You can check out some examples of golfing at StackExchange CodeGolf, but fair warning quiet a lot of them will make your head explode. What I propose is that we have a Golfing challenge of our own here. Take any problem from any of the units, and golf it. You can use homeworks that have been closed - That means (as of right now) questions from homework 1 are allowed, but not from homework 2. Solutions that I find delightful might get rewarded some karma by me, so get cracking golfing! Golfing Tips Use short 1 character function/variable names instead of long, descriptive ones - Instead of number, use n. In place of n1, n2, use x, y. If an else is not required, then don't use it. For more tips on Golfing in Python, check out this thread - Tips for Golfing in Python Format The problem that you're golfing. X Characters   Explanation, if required/asked. PS : This question was inspired because of this question by @robmurtha asked 05 Mar '12, 11:47 elssar 19.3k●25●63●155 accept rate: 52% Cool challenge! I'll enjoy watching the solutions, but I'm not even going to try (yet). Maybe in the weeks to come. (05 Mar '12, 11:48) James Viebke 2 Although the challenge sounds like fun, I think I'll give it a miss until I understand what good, readable code is so that I know when what I'm writing is poor code from a maintenance point of view. I don't want to get into bad habits! (05 Mar '12, 11:52) fnenu-1 ♦♦ 1 @fnenu Think of it as a way to challenge yourself to find innovative solutions. Short code doesn't necessarily mean bad bad. (05 Mar '12, 11:55) elssar 1 Isn't just using short variables a bad thing? I guess the problems themselves might be interesting to try. (05 Mar '12, 12:00) fnenu-1 ♦♦ 1 @fnenu it's a bad thing if you make it a habit. Also, sometimes it's a good thing, like n, x for number or s for string. i, j for iterating in loops or for indexes in arrays/lists/strings. (05 Mar '12, 12:06) elssar Why not choose an assignment and then have everyone golf the same one? It's hard to compare entries if they solve different problems. (05 Mar '12, 12:09) Anton Golov ♦ @jesyspa because it's not an objective challenge. It's just a place to have fun with your code & show off a little. (05 Mar '12, 12:11) elssar 1 for simple problems, like computing simple mathematical functions, using short names (even one-letter names) is fine and the resulting shortest expression is, in my opinion, still fun to look at because you get to understand it after a bit of looking at it. for more complicated problems, it's not as much fun, because often the solution is so obfuscated, it's not even interesting to read it (unless it's a truly remarkable thing it is doing... i've seen some one-liners used to separate different humans voices in a recording... now that's really neat!) (05 Mar '12, 15:11) Willebaldo G... 1 Short names aren't so bad; what's bad is naming all your variables things like IOOIIIOO and OIOOOIIOI. When I was a student at K-State, one of the systems programmers quit or was fired. He "kicked the wastebasket" on the way out, running a small piece of code that remapped all tokens in the operating system routines to such names. The code still ran, but... I think it took about two days to fully recover the system. (22 Mar '12, 13:22) Kenneth I. L... @kilaws: Double fun in cases where only the first six letters are considered during lookup. :D (22 Mar '12, 13:29) Anton Golov ♦ Heh, reminds me of a part, I think at the start, from the autobiography from Ejovi Nuwere, where he was hired to revoke all access a programmer or sys admin had while he was getting fired. (22 Mar '12, 13:38) elssar showing 10 of 11 show 1 more comments

 2 Calculating the factorial of a number 26 Characters f=lambda n:n<2 or n*f(n-1) answered 05 Mar '12, 15:04 Willebaldo G... 114●2 elssar 19.3k●25●63●155 Only problem is that it doesn't handle f(0). Fix that, with less characters than mine & you get some karma (05 Mar '12, 15:20) elssar 1 It's true that f(0) evaluates to True, but it's also true that in Python True == 1, so for all practical uses the definition is just as good as any other. Nonetheless, here's a definition that beats your 31-char solution under your constraints (just by one char, but hey, one char shorter still counts, haha!): 30 Characters f=lambda n:n and n*f(n-1) or 1 (05 Mar '12, 15:34) Willebaldo G... Points awarded, as promised :) (05 Mar '12, 15:37) elssar aha! So you decided to join codegolf SE. (06 Mar '12, 07:09) elssar you can lose 1 char by removing space here "n<2 or" (28 Mar '12, 05:06) EnTerr
 1 Homework 2.6, find last 31 characters (23 if we rename the function) find_last=lambda s,t:s.rfind(t)  answered 08 Mar '12, 01:11 Anton Golov ♦ 13.3k●21●74●174 nice. Awarded some points (08 Mar '12, 01:18) elssar For real?! How about 19 chars find_last=str.rfind (28 Mar '12, 00:17) EnTerr @EnTerr but then you don't have a function - no way to call it again. (28 Mar '12, 00:25) elssar @elssar: huh?! care to explain why you think so?  $find_last=str.rfind$ find_last('111','1') 2 \$ find_last('hello','hell') 0 (28 Mar '12, 04:40) EnTerr
 1 A Python interpreter (not contained in any of the units, but still fun IMHO) 57 Characters while True:exec '\n'.join(iter(lambda:raw_input('> '),''))  This is a read-eval-print loop. The '> ' string serves as a prompt for the interpreter-within-the-interpreter; you could of course just omit it and reduce the code to 53 characters. answered 27 Mar, 18:38 Michael Händel 7.7k●5●13
 1 Finding the factorial of a number. 28 Characters import math;f=math.factorial  answered 27 Mar, 18:48 Michael Händel 7.7k●5●13
 1 Find last, avoiding str.rfind 52 Characters f=lambda s,t:max(s.find(t,i) for i in range(len(s)))  answered 27 Mar, 19:08 Michael Händel 7.7k●5●13
 1 Finding the $n$-th Fibonacci number. 38 Characters f=lambda n:f(n-1)+f(n-2) if n>1 else n  answered 27 Mar, 19:35 Michael Händel 7.7k●5●13
 1 ps4-4 "Better Splitting" 125 Characters split_string=lambda s,p:reduce(lambda a,c:(a[0],a[1]+c) if c not in p else (a[0]+[a[1]],'') if a[1] else a,s+p[0],([],''))[0]  I kept the long function name split_string so that it still passes the grader. I provide an explanation in this thread. answered 26 Apr, 14:15 Michael Händel 7.7k●5●13 1 88 Characters split_string=lambda s,p:filter(bool,"".join([c,p[0]*2][c in p]for c in s).split(p[0]*2)) Converted from comment to answer and back again, but which is the preferred way to keep answers together? The commenting won't scale for longer code blocks, new answers are not kept together. Maybe 1 forum question for 1 actual problem with the tags codegolf, shorter and spoilers? And maybe it will start the integration of all the "shorter way to do x" questions. One downside that I see is that it would mix the Pythonic answers with the mangled code-golf anwers. Maybe we can have a convention to start all short solutions from a Pythonic one. (27 Apr, 02:22) yihong 1 And I thought my solution was short... :) Well done. What I don't understand is, why p[0]*2 and not just p[0]? The grader seems to be perfectly happy with 84 Characters split_string=lambda s,p:filter(bool,"".join([c,p[0]][c in p]for c in s).split(p[0])) As to your organizational questions, maybe @elssar in his capacity as creator of this thread should make a decision. I like the idea of the codegolf tag, but I suspect introducing a unified tag system into the forums will be the same sort of tilting at windmills as trying to make people post their code with all the indentations included. (27 Apr, 03:21) Michael Händel I think you are right about the p[0]*2 vs p[0]. It's a relic from earlier iterations that's no longer required. (27 Apr, 04:36) yihong You could shave quiet a few characters by using 1 letter variable names. @yihong that really should be an answer so that it can be upvoted I don't have dominion over all golf posts on Udacity forums. If you want to create a new post for every problem(or the ones good for golfing) then go ahead :) And it makes sense to have a unified tag for codegolf. Even if only a few people use it, it would be nice to have. (30 Apr, 22:44) elssar
 1 unit6-10 "Palindromes", using the recursive strategy sketched in the specification 63 Characters is_palindrome=i=lambda s:len(s)<2 or(s[0]==s[-1]and i(s[1:-1]))  unit6-10 "Palindromes", not using the recursive strategy sketched in the specification 33 Characters is_palindrome=lambda s:s==s[::-1]  answered 02 May, 17:11 Michael Händel 7.7k●5●13
 0 Looks like I'll have to get the ball rolling. Finding the factorial of a number. 36 Characters def f(n):return n*f(n-1) if n else 1  Explanation here Rewriting using lambda 31 Characters f=lambda n:n*f(n-1) if n else 1  answered 05 Mar '12, 12:09 elssar 19.3k●25●63●155
Question text:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "Title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported

### Tags:

×15,355
×134
×1
×1

Asked: 05 Mar '12, 11:47

Seen: 862 times

Last updated: 02 May, 17:22