Let's Golf! [Challenge]

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

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

   <code>

Explanation, if required/asked.

PS : This question was inspired because of this question by @robmurtha

asked 05 Mar '12, 11:47

elssar's gravatar image

elssar
21.0k2566158

accept rate: 52%

retagged 30 Apr '13, 22:44

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)

Jim V

Jim%20V's gravatar image
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 ♦♦

fnenu-1's gravatar image
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

elssar's gravatar image
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 ♦♦

fnenu-1's gravatar image
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

elssar's gravatar image

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 ♦

Anton%20Golov's gravatar image

@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

elssar's gravatar image
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...

Willebaldo%20Gomez's gravatar image
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...

Kenneth%20I.%20Laws-1's gravatar image

@kilaws: Double fun in cases where only the first six letters are considered during lookup. :D

(22 Mar '12, 13:29)

Anton Golov ♦

Anton%20Golov's gravatar image

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

elssar's gravatar image
1

hey golfers, check this out: http://keleshev.com/dissecting-a-code-golf-challenge
it gets pretty sick at the end ;)

(24 Mar, 09:22)

yihong

yihong's gravatar image
showing 10 of 12 show 2 more comments

13 Answers:

12next »

Calculating the factorial of a number

26 Characters

f=lambda n:n<2 or n*f(n-1)

link

answered 05 Mar '12, 15:04

Willebaldo%20Gomez's gravatar image

Willebaldo G...
1142

edited 05 Mar '12, 15:15

elssar's gravatar image

elssar
21.0k2566158

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

elssar's gravatar image
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...

Willebaldo%20Gomez's gravatar image

Points awarded, as promised :)

(05 Mar '12, 15:37)

elssar

elssar's gravatar image

aha! So you decided to join codegolf SE.

(06 Mar '12, 07:09)

elssar

elssar's gravatar image

you can lose 1 char by removing space here "n<2 or"

(28 Mar '12, 05:06)

EnTerr

EnTerr's gravatar image

Here's a function that takes a webpage and extracts all the links in the format we're currently using:

63 58 characters

c=lambda p:[x[9:-2]for x in re.findall('<a href=".*?">',p)]

It assumes that there has already been an import re (because who does anything without import re, anyway? :P).

(To clarify, this is a variation of the print_all_links function in 2.30, but which returns a list as that's less characters more useful.)

link

answered 05 Mar '12, 12:49

Anton%20Golov's gravatar image

Anton Golov ♦
13.7k2175174

edited 05 Mar '12, 12:56

Nice, think I'll rewrite my factorial code using lambda.

(05 Mar '12, 13:07)

elssar

elssar's gravatar image

Homework 2.6, find last

31 characters (23 if we rename the function)

find_last=lambda s,t:s.rfind(t)

link

answered 08 Mar '12, 01:11

Anton%20Golov's gravatar image

Anton Golov ♦
13.7k2175174

nice. Awarded some points

(08 Mar '12, 01:18)

elssar

elssar's gravatar image

For real?! How about 19 chars

find_last=str.rfind

(28 Mar '12, 00:17)

EnTerr

EnTerr's gravatar image

@EnTerr but then you don't have a function - no way to call it again.

(28 Mar '12, 00:25)

elssar

elssar's gravatar image

@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

EnTerr's gravatar image

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.

link

answered 27 Mar '13, 18:38

Michael%20H%C3%A4ndel's gravatar image

Michael Händel
23.7k1843

edited 27 Mar '13, 18:52

Finding the factorial of a number.

28 Characters

import math;f=math.factorial

link

answered 27 Mar '13, 18:48

Michael%20H%C3%A4ndel's gravatar image

Michael Händel
23.7k1843

edited 27 Mar '13, 19:11

Find last, avoiding str.rfind

52 Characters

f=lambda s,t:max(s.find(t,i) for i in range(len(s)))

link

answered 27 Mar '13, 19:08

Michael%20H%C3%A4ndel's gravatar image

Michael Händel
23.7k1843

Finding the $%n$%-th Fibonacci number.

38 Characters

f=lambda n:f(n-1)+f(n-2) if n>1 else n

link

answered 27 Mar '13, 19:35

Michael%20H%C3%A4ndel's gravatar image

Michael Händel
23.7k1843

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.

link

answered 26 Apr '13, 14:15

Michael%20H%C3%A4ndel's gravatar image

Michael Händel
23.7k1843

edited 26 Apr '13, 14:17

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 '13, 02:22)

yihong

yihong's gravatar image
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 '13, 03:21)

Michael Händel

Michael%20H%C3%A4ndel's gravatar image

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 '13, 04:36)

yihong

yihong's gravatar image
  1. You could shave quiet a few characters by using 1 letter variable names.
  2. @yihong that really should be an answer so that it can be upvoted
  3. 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 '13, 22:44)

elssar

elssar's gravatar image

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]

link

answered 02 May '13, 17:11

Michael%20H%C3%A4ndel's gravatar image

Michael Händel
23.7k1843

edited 02 May '13, 17:22

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

link

answered 05 Mar '12, 12:09

elssar's gravatar image

elssar
21.0k2566158

edited 05 Mar '12, 13:08

Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • 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

×29,744
×193
×1
×1

Asked: 05 Mar '12, 11:47

Seen: 1,187 times

Last updated: 24 Mar, 09:22