text:
How to golf string output in Chef
I'm attempting to solve a programming golf style programming puzzle. I need to write an 18 character phrase in Chef in less than 32 "lines" of code. In this case, a line counts as an ingredient or an instruction.
The most straightforward way of doing this is to declare an ingredient for each character and put each ingredient into a baking dish. Unfortunately for what I'm trying to do, that takes too many "lines" of code. (I'm limited to 32 and I want to print a 18 character phrase. 18*2 + title + serves command + headers = 40).
Here are things I tried:
So I had the idea of just using large numbers that would span multiple unicode chars. But when I print it out, I get garbage. So then I had the idea to just stream my characters by reading off each byte of a large number at a time and popping them into a baking dish in a loop. Unfortunately, there doesn't seem to be a way to do with the operators I have (the basic four arithmetic operators). I tried taking a number, dividing by 256, multiplying by 256, and subtracting that from my original number to get the least significant byte, but then discovered that Chef uses floating point (that is the number doesn't change).
There are no logical operators. There's no comparison operators. Any idea on what I can try next to print out an 18 character phrase in less than 32 "lines" of code? (Putting commands on the same line doesn't help. It still counts the same).

Outside the box: What interpreter are you using? I don't see anything in the spec that requires Chef to use floating point. If you write your own interpreter using integers...

I'm unsure why help solving a programming golf problem is considered off topic here. I would consider it off topic on StackOverflow. I'll edit it to make it clear I'm solving a programming puzzle.

The questions seems little legit. If you can modify it and turn it into a programming challenge with shortest code as scoring criteria and other rules, then it can be reopened. As of right now, it simply looks like you need help in doing some stuff, even though the question is nice.

@Optimizer Not all questions need to be challenges. @ Jason It might help if you post the code you're currently trying to golf. What works for one string may not work for another (due to patterns or whatever). It also changes it from general advice to "I have this code that works correctly and I'm trying to golf it to X lines/characters", which may be received better.

Ah... Okay, @Optimizer. I guess I misinterpreted the part of the help area that said, "Non-challenge questions that are are related to solving programming puzzles or a particular type of challenge are also on topic." Perhaps that's another challenge for me to figure out. ;) I'll reword it.

Right now it seems there's a fine line between "non-challenge" and "general programming" questions that is hard to navigate. Hopefully we'll have clearer rules in the future.

I'll take @Geobits advice and post some code examples. If you guys wouldn't mind, please don't outright delete this question until I get a chance to go home and link to some of my attempts.

There would have to be some kind of exploitable sequence in the characters. Within the "Chef" rules, I don't see it's feasible to encode an arbitrary string with more than one character per ingredient.

If Chef had a way of extracting a byte from a multibyte num then one could encode an arbitrary string easily. One could use a loop to extract each byte. Unfortunately, there is no AND operator and the numbers (at least in the Perl interpreter) are floats.
One other thing that may have worked, but didn't is that it looks like arithmetic operations in Chef cause the answer to be pushed on top of the operand already in the stack. (that is peek, add, push), but the Perl interpreter does pop, add, push.

Can you post the 18 character that you want to write? Or do you want a method that will work for any 18 character string?

The competition is over, but it would still be interesting to learn what the solution could have been. Ultimately, I wanted to print "Engineering Health" on the screen. Here's a link to the gist that has my submission to the competition. https://gist.github.com/CernerJT/80198257abc36cc4c3b3
What I did to solve it was to not care about capitalization and to remove the space. I thought it would be much more amazing to have been able to write a program that could take any arbitrary string and print it out.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Notes to Tablature
Challenge
Given a list a notes, you must return the corresponding tablature.
Notes
The notes must be in the range of A to G inclusive and the octave range being 2 to 6 inclusive. The format is note-octave with # representing a sharp and b representing a flat. E.g: A7 or F#3.
Tabs
Tablature is a method of writing music, by diagrammatically representing the instrument. It is usually represented as five lines with numbers on them.
The numbers that are written on the lines represent the fret used to obtain the desired pitch. For example, the number 3 written on the top line of the staff indicates that the player should press down at the third fret on the high E (first string). Number 0 denotes the nut — that is, an open string.
Fret numbers may not be greater than 22 and the guitar is six string.
The tablature must be in the standard ASCII format. You must not include any technique indicators (hammer on, slide etc.). Separate each note by five dashes. In the case of double digits, reduce the number of dashes to four.
The beginning of the tab should look like this:
e |-----
B |-----
G |-----
D |-----
A |-----
E |-----

And the end should look like:
-----|

for all lines.

(source: justinguitar.com)
Example
Input: C3 C3 D3 E3 F3

Output:

e |-----------------------------------|
B |-----------------------------------|
G |-----------------------------------|
D |-----------------0-----2-----3-----|
A |-----3-----3-----------------------|
E |-----------------------------------|

Winning
The shortest code wins

Do we need to use appropriate strings in our output?  What's to stop us from outputting tablature that only uses the E string?

@crazedgremlin You need to take into account the octaves. Only using the E string means that the note wouldn't be in the appropriate octave.

To raise a note by one octave, we could add 12 frets to the fret value.  Is there a rule to prevent this that I missed?

@crazedgremlin You may, but this only provides two octaves.

I'm just being pedantic, but you never said I can't have a really long guitar with 1000 frets.

@crazedgremlin Haha I've edited that in, but I'd love to see a thousand fret guitar :)

@steveverrill A double-neck guitar, combining a five string bass and standard tuning 24-fret guitar, could potentially span B0 to E6...

There were no close votes yesterday, when the question was being clarified. Would today's close voters care to explain what the problem is? I'm deleting my clarifications because as far as I am concerned the question is now pretty clear. The only things I can see wrong are that the range of a 22-fret guitar is exactly E2 to D6 (not complete octaves 2 and 6) and the I/O is not defined (I assume commandline,stdin,function argument are all acceptable, as well as stdout or function return.)

Ok, there is another guitar tab question in the Related but it is completely different: it asks for chords, whereas this one asks for melody notes in specific octaves. This is not a duplicate of that one. Speak up before you closevote and these things can be clarified!

I assume we need to use standard tuning? ;)

@ValentinGrégoire Yep :)

Python 3 – 329 328 319 300
This is my first post on codegolf.se, and probably not nearly optimal; I have read a lot of posts here but did my first code golf ever maybe 50 hours ago. Wanted to try, though!
EDIT: Removed 1 byte, didn't need to output an extra dash there
EDIT 2: Removed 9 bytes, removed some spaces from the note string
EDIT 3: Removed 19 bytes by converting filter() to a generator
a,b='C B#oC#DboD oD#EboE FboF E#oF#GboG oG#AboA oA#BboB Cb',input().split()
for f in range(6):print('eBGDAE'[f]+' |-----'+''.join([((str(d[-1])if f==6-len(d)else'')+'-'*6)[:6]for d in[[c-d+9for d in b"%*/48="if c+9>=d]for c in[12*int(g[-1])+a[:a.index((g[:-1]+' ')[:2])].count('o')for g in b]]])+'|')

A bit ungolfed:
a='C B#oC#DboD oD#EboE FboF E#oF#GboG oG#AboA oA#BboB Cb' # string of notes
b=input().split()                                         # read user input
for f in range(6):                    # loop through the strings

  print('eBGDAE'[f] + ' |-----' +     # string identifier and start of string
  ''.join([                           # join notes of tablature
  ((str(d[-1])                        # highest string the note can be played on
  if f == 6 - len(d)                  # if this is the correct string print the fret
  else '')                            # if not then only dashes
  + '-' * 6)                          # print the dashes after the fret
  [:6]                                # but only until 6 chars per note

  for d in [                          # loop through strings
  [c - d                              # calculate fret number
  + 9                                 # add back the 9 (explained below)
  for d in b"%*/48="                  # string values increased by 9 as ASCII bytes
  if c + 9 >= d]                      # filter to remove too high-pitched strings

  for c in [                          # loop through note values
  12 * int(g[-1]) +                   # octave value
  a[:a.index(                         # part of note string before this note
  (g[:-1] + ' ')[:2])]                # unique note identifier
  .count('o')                         # o's (frets) between C and this note
  for g in b]]])                      # loop through notes

  + '|')                              # end tablature

This is brilliant! :)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

authors: Николай Елисеев

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Animating the Separation of Fluids by Density
Let the characters 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ represent the particles of 36 immiscible fluids, each more dense than the last. So the 0 fluid is the least dense and floats on all the others, while Z is the densest and always sinks.
Let # represent a solid particle that cannot move at all..
Consider a rectangular grid of some of these 37 characters, with anything out of bounds treated as #. Gravity will want to stabilize them with the least dense fluids on top and the most dense on the bottom.
Our procedure for stabilization is:

Choose a random grid cell c that is not a # and has a density greater than that of at least one of the 3 neighboring cells on the layer below it (southwest, south, and southeast) that is not a #.
Stop procedure if no such choice exists.
Let d be a cell randomly sampled from these valid neighboring cells with the least densities.
Swap the values at c and d.
Repeat procedure until it has stopped.

Example
Running the procedure on
A01
#10
020

might start out step 1 by selecting the A. There is only one cell below it with smaller density so the next grid would be
101
#A0
020

The procedure might continue on as
101 100 000 000
#00 #01 #11 #01
A20 A20 A20 A21

The last arrangement being stable.
Challenge
Write a program that takes in a rectangular string of the 37 characters via stdin, command line, or function call. Initially, the given grid should be printed to stdout, but each time Enter is hit, one swap (step 3) should be done and the grid reprinted, separated from the last grid by an empty line. When the grid with no more possible swaps is printed (the end of the procedure) the program immediately ends.

Grid dimensions will be 1×1 at minimum, and have no maximum size (as limited by Int.Max or computer memory). The grid is not always square.
You can assume valid input. The grid will always be perfectly rectangular, containing only uppercase alphanumeric characters and #.
You may use a key besides Enter if it is more convenient.
Your program must follow [something equivalent to] the stabilization procedure, including using [pseudo]randomness for steps 1 and 2.
In the input (but not the output) underscores (_) may be used instead of newlines.

Scoring
This is code-golf, so the shortest code in bytes wins. There are bonuses however.
Bonus 1 - Horizontal periodic boundary conditions: (minus 30 bytes)
Instead of treating the left and right out of bounds areas as #, connect them with PBC. There should be an option in your code where changing something like 0 to 1 or False to True enables or disables the PBC.
Bonus 2 - Graphics instead of text: (minus 100 bytes)
Instead of using blocks of text, use images (of any common truecolor format). Represent 0...Z with 36 distinct but related colors, e.g. a gradient from white to dark blue, and # with some other distinct color like dark red.
The program behaves the same way except now an image is either saved to a file (it may be the same file each time) or displayed to the screen for each grid swap in place of any textual output. The input may still be textual or some valid image, your choice.
Whether you do this bonus or not, giving output examples is highly encouraged.

It will be difficult to distinguish end of input.  We can't read to eof because we need to wait for enter on stdin.  Can we use a row count, or advance the simulation on a time step?

@KeithRandall You'll know that the input is over when you receive a blank line on stdin, which signals that you should output the iteration.

Can we print all iterations at once instead of relying on Enter key ?

@Optimizer Nope

Python, 300 298 chars
import random
C=random.choice
R=raw_input
G=list(R().replace('_','\n'))
S=w=G.index('\n')
while S:
 print''.join(G);S=[];R()
 for i,c in enumerate(G):
    B=[(d,j)for j,d in enumerate(G[i+w:i+w+3])if'/'<d<c]
    if B:S+=[(i,[i+w+j for d,j in B if d==min(B)[0]])]
 if S:i,B=C(S);j=C(B);G[i],G[j]=G[j],G[i]

Run it like cat inputfile - | fluid.py.  The input file should be a single line using _ as a line separator.

You can save two bytes by doing S=R=raw_input instead of S=1

http://pastebin.com/6BQJGAxc With these modifications, it is down to 285 chars. The input file is still delimited by _ but must now also end with a trailing _. A full input file could thus look like A01_#10_020_\n


text:
Give me a haircut!
This is my head:
\         /-- -|
 /   -\  |  |  |
\      \ \  \  |
 --\    | \  | |
    / |--| / / |
 /|-  //--| /  |
| |  ||   //\  |
| \  /|  //  \ |

It consists of exactly eight hairs. My hair is too long. Please cut each individual strand to a length I specify.
Input
The main attraction in this section is the actual head of hair. Here's a graphical, color-coded representation, along with an animation, for the lazy:

And here is a full specification for what a set of hairs is:

The individual hairs, which we will call strands, will be made out of the /, \, |, and - ASCII characters, henceforth known as atoms.
The entire head of hear (all of the strands combined) will be c columns by r rows, where c ≥ 1 and r ≥ 2.
Each strand will...

start at the last row of the head (row r - 1).
have a length l where l ≥ 2.

Strands may be parsed with the following method:

Start at the bottom of the strand. This will be a /, |, or \ atom, which we will call the root. (Strands are parsed from left to right, ordered by the root.)
Find the atom that points towards the root.

A | atom points up and down. A - atom points left and right (but can never point to the root since only roots can be in the bottom row). A / atom points left-down and up-right, and a \ atom does the opposite.
There will always be exactly one atom that points towards the root atom.

Find an unused atom (one that is not yet part of any strand) that points towards this atom and is also not below this atom (hair can't grow downwards, but sideways is okay).

If there are zero, you have reached the end of the strand!
If there is one, this is the next atom of the strand. Repeat step 3 with this atom. (This atom is now marked as "used" for the purposes of step 3, since it's part of a strand.)
There will never be multiple unused atoms here at any point in the head.

The input format will be:

A head of hair. Can be input as-is (multiline input with literal newlines), or with a delimiter of your choice in place of newlines. Note that the head will always be a rectangle; i.e. trailing whitespace will be added as necessary (the weird straight line hair at the right is just to eliminate extra trailing whitespace to avoid confusion).
A number ≥ 1 specifying how much hair to cut. This will be described in detail in the next section.

You may accept input to a function, use STDIN/STDOUT, etc. (anything reasonable).
Output
Your output will be the head of hair with the haircut applied. To give a haircut, simply reduce the length of each strand of hair by the amount specified (which will always be 1 or greater), starting from the endpoint of the hair moving towards the root. However, always leave the root intact!
Here's a simple example. Say the input for the head is
\
 /
|
|

With a second input of 2, you would cut two atoms from the strand and get a result of
|
|

And with an input of 42, the output would just be
|

Note that whitespace before and after the head is completely irrelevant; you can trim extra newlines or you could add more padding. It doesn't matter, as long as the head remains intact. (You may do whatever you want with trailing whitespace as well.)
Test Cases
For all test cases, the example presented at the very beginning of this post will be used.
Haircut length = 1:
          /-   |
 /    \  |     |
\      \ \  \  |
 --\    | \  | |
    / |--  / / |
  |-  //--| /  |
| |  ||   //   |
| \  /|  //  \ |

Length of 3:
         |
         \     |
 --\    | \    |
    / |--  / / |
  |-  //  | /  |
  |  ||   //   |
| \  /|  //  \ |

Length of 7:
  |-  /   |
  |  |    /    |
| \  /|  //  \ |

Length of 1337:
| \  /|  //  \ |

Scoring
This is code-golf, so the shortest code in bytes will win!

Are there atoms '-' in the bottom row? Point 2 seems to say yes, point 1 seems to say no.

@edc65 No, there are not. (Edited to clarify)

I think there is a mistake in the test case. On the fourth row from the bottom, the - in the third strand from the left points at the | in the fourth strand from the left

@feersum Correct. The path is determined by what points to the -, not what it points to. For example, the | doesn't point to the / in the first strand, but it is pointed to by the /. (Yes, I know it's confusing; I had to redo the GIF several times because I confused even myself!) An easier way to understand this might be just to look at the top of the second strand.

I know it is determined by later pieces pointing to earlier ones. My argument is that the - should be joined to the fourth strand, not the third.

@feersum Ah, I see what you're saying. Note these clauses in the specification: "Strands are parsed from left to right, ordered by the root" and "Find an unused atom (one that is not yet part of any strand)". Since the third strand is parsed before the first, it gets that - instead of the fourth.

Huh. I tried to check for a left-to-right rule a couple of times but could not find one...Better delete my answer then.

JavaScript (E6) 195 212 222 232
Using a recursive function R to find the path of each strand and marking the positions starting from 1 for the farest from the root. Then it's easy, in a second pass, to substitute the lower marked position with blanks.
F=(h,t,
   n=[...h],c=h.search('\n'),
   R=p=>[1,-1,c+2,c+1,c].some((d,i)=>n[p-d]=='--\\|/'[i]?n[p-=d]=1:0)&&R(p)+(R[p]=l++)
  )=>
  n.map((v,p)=>R[p]<t?' ':h[p],n.map((a,p)=>!h[p+c]&a>' '&&R(p,l=0))).join('')

Test in FireFox/FireBug console
head = "\\         /-- -|\n /   -\\  |  |  |\n\\      \\ \\  \\  |\n --\\    | \\  | |\n    / |--| / / |\n /|-  //--| /  |\n| |  ||   //\\  |\n| \\  /|  //  \\ |";
console.log(F(head,0))
console.log(F(head,1))
console.log(F(head,3))
console.log(F(head,7))
console.log(F(head, 1337))

Output
\         /-- -|
 /   -\  |  |  |
\      \ \  \  |
 --\    | \  | |
    / |--| / / |
 /|-  //--| /  |
| |  ||   //\  |
| \  /|  //  \ |

          /-   |
 /    \  |     |
\      \ \  \  |
 --\    | \  | |
    / |--  / / |
  |-  //--| /  |
| |  ||   //   |
| \  /|  //  \ |

         |
         \     |
 --\    | \    |
    / |--  / / |
  |-  //  | /  |
  |  ||   //   |
| \  /|  //  \ |

  |-  /   |
  |  |    /    |
| \  /|  //  \ |

| \  /|  //  \ |


text:
Tips for Golfing in BBC BASIC
What general tips do you have for golfing in BBC BASIC? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to BBC BASIC (e.g. "remove comments" is not an answer).

As a general comment, BBC Basic (and other old school Basics like C64 Basic and Spectrum Basic) are great for golfing graphics problems. There's no need to set up any parameters, because back when these machines were made, you had what the hardware gave you. On the other hand, they are also good general-purpose programming languages, not like some of the dedicated graphics languages (LOGO etc) which can be quite hard to do general purpose programming in. I will post some answers later.

Spaces after keywords are optional because of tokenisation. For example:
INPUT answer$
PRINT answer$
IF answer$ = 'Hi' THEN
  PRINT 'Hi!'
ENDIF

Can be shortened to
INPUTanswer$
PRINTanswer$
IFanswer$='Hi'THEN
  PRINT'Hi!'
ENDIF

The corollary of this is, a variable name cannot start with a keyword. So PRINTa is not a valid variable name. However printa is.
Spaces before keywords can be more tricky. Variable names can end with a keyword, so if variable name and keyword are run together they will be interpreted as a variable name.
For example the following gives a "no such variable" error because the variable aPRINT is not defined:
  a=7
  IF7=aPRINT"seven"

By rearranging this can be avoided:
  a=7
  IFa=7PRINT"seven"

This is a trivial example, but frequently rearranging an expression to end in a number or bracket instead of a variable name will enable you to eliminate a trailing space.

I'd love to see the parser code that allows this mess.

Choose your interpreter well.
Very few of us have access to an original BBC micro, There's a whole range of interpreters at http://www.bbcbasic.co.uk/bbcbasic.html . Each implementation is slightly different.
My preferred interpreter is the first one on the list, "BBC Basic for Windows" written by RT Russell and available for Linux through Wine. It covers virtually all the features of original BBC Basic, including for example sound through the windows API, and has many enhancements. Its IDE and help are easy to use and feature packed.
It frequently allows you to omit colons between statements (which other implementations also do to some extent, but less) and it does not require you to number the lines of your program. On the downside, it only handles strings up to 255 characters and the evaluation version is restricted to 16k memory.
The other major family of BBC basics is Brandy Basic and its derivatives. Written in C, this is extremely portable, but has less features. For example it does not include sound, and rather than simply ignoring sound commands the program crashes. It is however able to handle longer strings than R T Russell's implementation so I have used it on occasion. There is no modern IDE, but it replicates BBC Basic's commandline fairly well (so it's not difficult to use if you are already familiar with BBC Basic.)

Use VDU codes to perform graphics tasks.
All graphics in BBC basic was performed via machine-specific ASCII control characters. The VDU command exists to enable you to pass ASCII characters direct to the video controller.
For example in PLOT101,500,300 (draw a rectangle whose diagonal corners are the last position of the graphics cursor and the new point 500,300) can be subsituted by VDU25,101,500;300; The coordinates are followed by ; because they are double byte values. We can also replace 25,101, by 25881; which is the 16-bit little-endian representation of these 2 bytes.
Although this actually makes things longer when you have only one PLOT statement, if you have several it is shorter. When you have a long string of VDU codes every PLOT can be replaced by 25, (or if you declare a=25 simply by a,)
Here's an example of this technique: https://codegolf.stackexchange.com/a/26732/15599
Note that this is not just limited to PLOT. MODE, GCOL, COLOUR, ORIGIN etc can all work out shorter when expressed as a series of numeric values in a long VDU statement.

Use FN instead of PROC or GOSUB
GOSUB is very old fashioned. it requires a line number, so you have the following:
    GOSUB90
    .
    .
 90 dosomething
    RETURN

7 characters to call, 8 characters to define and return.
PROC doesnt require a line number. Here you have
    PROCa(x,y,z)
    .
    .
    DEFPROCa(x,y,z)
    dosomething
    ENDPROC

5 characters to call (excluding arguments), 13 characters to define and return
With FN you have
    q=FNa(x,y,z)
    .
    .
    DEFFNa(x,y,z)
    dosomething
    =1

5 characters to call (excluding arguments, but including the obligatory use of the return value.) 8 characters to define and return
FN wins pretty much all the time, especially if you can make use of the return value. If you have no arguments you can omit the brackets.

Use Abbreviated Keywords
Surprised this wasn't mentioned before, but BBC Basic supports abbreviated versions of keywords so that, eg:
1 FOR X=1 TO 10 STEP 2:PRINT X:NEXT X
Can be rewritten as (omitting space where possible too):
1F.X=1TO10S.2:P.X:N.X
Some keywords don't have abbreviations (eg, IF). The complete list is in the BBC Basic manual chapter 48, there's a handy copy here too.
The most surprising part is that abbreviations for some functions include the opening parenthesis, eg: PRINT MID$("HELLO",3,2) is abbreviated as P.M."HELLO",3,2) - note the closing parenthesis is required even though the opening one was abbreviated away.

Damn I did not know these existed

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Tips for golfing in Pyth
Pyth is a Python-inspired procedural programming language, created by PPCG user isaacg.
What general tips do you have for golfing in Pyth? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pyth.
One tip per answer, please.

Write the code in Python first
Pyth is so similar to Python that it is pretty easy to translate Python programs to Pyth. However, because Pyth is a single-letter-per-command language, it is sometimes hard to write straight Pyth. By writing in Python first, there is less to think about at a time (since Python is a pretty easy language to code in).

You could also mention that you can still use Python syntax in Pyth, so you can convert parts of the program individually or just use python if necessary. (As you did here)

@mbomb007 Download the Pyth interpreter and read through the documents. That's the only reliable way I know for writing a Pyth program.

@mbomb007 Sorry; that's the way I learned how to write Pyth (looking through the source code). There is basically no documentation on Pyth; you basically have to learn the syntax by trial and error.

Nowadays it might be better to write it in big-pyth format first since it can be translated instantly

Know Your Variables
Pyth has 3 categories of variables: generic pre-initialized variables, variables pre-initialized based on user input, and variables that implicitly generate an assignment on first use.
Generic variables:
b = "\n"
d = " "
k = ""
G = "abcdefghijklmnopqrstuvwxyz"
H = {}                            # (empty dict)
N = '"'
T = 10
Y = []
Z = 0

Input-initialized variables:
Q = eval(input())
z = input()

Note that these initializations will only be run in a given program if the associated variable is used outside of a string in the code. In addition, the order is Q, then z, if both are used.
Assignment on first use variables:
J and K. If you want to initialize them both to the same value, you can do so with an expression such as KJ0, which is equivalent to the lengthier J0K0.

Use the even newer online interpreter to test your answers.
Note that this is new software, so it may be buggy. Please report any problems to me.

Awesome! I couldn't find this with google, just what I needed!

Strings at the end of the line don't need end quotes. For example:
"Hello, world!

is a completely valid Hello World program.

Quite obvious really, it is the first google result for "Pyth programming language". Did you create your own page on esolangs?

@theonlygusti Yes, I did. Also, it wasn't the first result last October.

Use C for base compression
This is actually undocumented, C on a string is actually not direct chr -> int but instead base 256 -> base 10 (which is the same on one char strings). This is hugely helpful in compressing an int, we can use this script to compress:
sCMjQ256

Take 12345678910, it results in ßÜ> (some unprintables in there).
Also with an array of ints, you can concatenate them, and with large strings by converting to code points and treating as base 128 number.
Another usage of C, thanks @xnor for showing me this, is making an arbitrary large number. The naive way is:
^TT

But we can do one byte better with:
CG

this base 256 deconverts the entire alphabet. Results 156490583352162063278528710879425690470022892627113539022649722 = ~1.56e62.

Added to doc now.

Use the short functional...err...functions
When the lambda argument to map or reduce just applies one operation to the arguments,, you can use the short forms, M and F. fMx is equivalent to mfdx, and fFx is the same thing as .UfbZx. For instance, say we take a list of numbers as input and output each one incremented. A first approach might be:
mhdQ

However, that can be rewritten as:
hMQ

A similar thing applies to reduce with F. As an example, say there's a challenge to calculate the product of a list of integers. Again, a first try may be:
.U*bZQ

However, with F, that can be shortened to:
*FQ

Shaves off three bytes...not bad!

And you don't need Q, as it is supplemented when the function is missing an input, making it *F

There is now an online tutorial for Pyth.
Full documentation will be added later.

Keep your Pyth implementation up to date.
I'm fairly regularly improving Pyth, removing less useful features and adding more useful ones, so keep an eye out for what's new and update your copy of the implementation regularly.
Some recently added features: (as of 10/19/14)
y: Acts as *2 on numbers, and as list of all subsets on strings and lists. For instance:
pyth -c 'y"abc'
['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']

f: f is normally the filter command. Now, when called with a number as its second argument, it will filter over the infinite sequence starting with that number and counting up by ones, then return the first element of the resulting sequence.
For instance, here's the code to find the smallest prime over a billion:
pyth -c 'f!tPT^T9'
1000000007

Those look like useful additions, but what can you use instead of the old yz? mvdczd can't be the shortest way...

@Dennis I threw out the old y because I don't think Pyth needs to have multiple super-easily parsed input formats, just one, e.g. the Python format. So, yes, I think mvdczd will have to do, unfortunately.

@Dennis Problem solved, just added this to r's string processing suite.

r looks pretty useful.

@isaacg Sorry if this is off-topic, but I am wondering how to use the root operation @ in Fdr1+1@Q2Iq%Qd0d to make a factor calculator. When I try to use it, it defaults to the index meaning instead. Is there any way around this behavior?

Look at all of the control flow options
Loops:
F: For loop. Just like Python's.
V: For loop over a range. Neither variable nor range must be given, so 2 characters shorter.
W: While loop. Just like Python's.
#: Infinite while loop. Escape with error or explicit break. Only try ... except feature now in Pyth.
Functions:
D: General define. Just like Python.
L: 1 argument, no assignment function, like Python's lambda, but named. Function name, variable name and return (R) need not be given, so 3 characters shorter.
Functional programming:
f: Filter - select elements of input sequence that return truthy on input lambda.
f: First integer greater than or equal to input which gives truthy filter result.
m: Map - transform elements of input sequence using input lambda.
u: Reduce - fold input sequence on input lambda, initializing accumulator to third argument.
o: Order - older elements of input sequence using input lambda as the key.
Usually, there will be multiple possibilities for any given problem, and only by writing test solutions with each of them can you figure out which is shortest.

.x can more recently be used for try-except blocks.

@mbomb007 is there way to neglect except block, I mean can that be left empty? For ex: .x{some_statments}{except_block - can this be empty}.

@GurupadMamadapur # ... B can be used this way if you're not inside an expression

Named arguments in functions (No longer supported)
Sometimes, default values in functions can be useful for golfing. Pyth actually supports this (much to my surprise). For example:
DC=Z1RZ;C;C5

Will print:
1
5

You can also use J and K to save characters when doing this:
DgJ1K1R+JKg;g2;g2 3

prints:
2
3
5

This is usually useful for recursive algorithms.
This no longer works, but I have left it here in case someone wants to golf using an old version of Pyth.

Wow - Even I didn't realize Pyth supported this, and I wrote the language!

Unfortunately, this no longer works in more recent versions of Pyth.

Should this tip be deleted like one of the other out-of-date tips? If not, maybe it should be marked with what version(s) this tip applies to.

@mbomb007 I've been meaning to find the version, but I've been too lazy. Ill delete it if you think it is better off that way until I do find it.

@FryAmTheEggman I think it's up to you, since it says in the title that it's not supported.

Unpacking 2 element tuples with F
Say you have a 2 element tuple, J = (a, b), and you want r(a,b), for some 2 arity function r.
The naive way to do this is rhJeJ.
The fancy way to do this is r.*J, using the unpack operator.
The really fancy way to do this is rFJ, using the fold operator.

is it still possible to use .u for that? .u seems to be cumulative reduce now.

.u -> .* this was a change that was made a while ago, but was never updated.

Use map to generate lists
It's basically an equivalent of the fancy list comprehensions of python. Use an existing list or an range to iterate over and map each value, even if the value doesn't matter.
Two examples:

Generate a list of 8 zeros.
mZ8 instead of *8]Z

Generate a list of 5 random numbers between 0 and 9:
mOT5 instead of V5~Y]OT)
The second one automatically assigns the list to Y (well actually it appends to Y), but even =YmOTU5 is shorter.

Use the short arithmetic functions
h: Other than returning the first element of a list, it increments a number, e.g. hT evaluates to 11. Shorter than +1T.
t: This decrements a number (other than return the tail of a list), e.g. tT evaluates to 9. Shorter than -T1.
y: This doubles a number, e.g. yT evaluates to 20, shorter than *T2 or +TT.

Implicit Q at EOF
This is a new change, as of today.
Q is the variable which is auto-initialized to the evaluated input. It is implicitly appended to the end of the Pyth program, as many times as is necessary to make the arity work out. To see an example of how to use this for golfing, let's say we want to compute the Collatz function of the input.
A shortest way to write it is like this:
@,/Q2h*3QQ

However, since the Qs are implicit at the end of the file, we can simply write:
@,/Q2h*3

Saving 2 bytes.
Note that functions with non-required arguments will not have those arguments filled in. For instance, c"12 12" will not have an implicit Q, since c only requires 1 argument.

Use reduce to apply a function repeatedly.
Suppose you need to set a variable to some function of itself, and repeat a certain number of times. Take, for instance, the problem of finding the number 100 later in the Collatz Sequence from the input. The shortest way to find the next number in the sequence, if the initial number is Q, is
@,/Q2h*Q3Q

The most obvious way to apply this 100 times and print the result would be
V100=Q@,/Q2h*Q3Q;Q

Loop 100 times, updating the value of Q each time, then end the loop and print Q.
Instead, we can use a reduce function which ignores the sequence variable (H).
u@,/G2h*G3GU100Q

This is 2 characters shorter. It is 3 characters shorter if you are trying to loop as many times as there are elements in a sequence.

Switching two elements in a list
Switching two elements can be quite an expensive task. So here are two approaches you wanna use.
Tmp-variable approach
In preparation we define a list Y and fill it with some numbers. The goal is to switch the second and third element.
=Y[1 3 5 3 6 7)AGH,1 2

We simply assign the tmp variable J = Q[G], do the first list assignment Y[G] = Y[H] and then the second last assignment Y[H] = J. The trick here is to nest the two list assignments, so you don't have to suppress printing and don't have to use refer twice to Y.
J@YGXXYG@YHHJ

instead of
J@YG XYG@YHXYHJ

Translating approach
If the elements, which you want to switch, are unique in the list, use this approach. It's really short. So this time we switch the first and third element (the values 1 and 5 are unique).
=Y[1 3 5 3 6 7)K,Z2

This uses the translation functionality of the list:
XYm@YdK)

This translating replaces every element Y[0] with Y[1] and every Y[1] with Y[0]. So if the values are not unique, bad things happend. For instance K,1 2 results in [1, 5, 3, 5, 6, 7].
Notice that the closing parentheses is optional, if the statement is the last one in your code.

There are usually shorter alternatives to Any
When you want to find if any of a sequence satisfy a condition, you would usually use .Em. For example, if you want to find out if any in a list are greater-than-or-equal to 5:
.Emgd5Q

But, if it only needs to be a truthy/falsey, not true/false, sm would work since sum works on bools.
smgd5Q

We can even do one shorter, with filter:
fgT5Q

The last one looks really ugly though.
For .All, the only thing I can think of is to use the opposite condition and negate it for a one char save over .Am:
!f<T5Q

Finding the maximum of two integers
g#

For instance, suppose you have J=5 and K=12. Then g#JK = 12, and g#KJ = 12 as well.
This was discovered by @Pietu1998, who put it this way:
Not sure if someone has already found it, but there's a cool way to do max(A, B) in 2 bytes, no need to use 3 for eS,AB. g#AB does the same thing. (It's very inefficient, though, since it loops max(1, A-B+1) times. An optimization is to put the number likely to be larger as B.)

@Jakube This is true. I apparently misthough something while typing this in chat.

Pyth's join method
The join method in Python can be often a little bit annoying, since it only joins strings. Pyth's join is more generous. It transforms all objects in strings by default.
E.g. jkUT gives 0123456789 or jb["abc"4,5\f]7 gives
abc
4
(5, 'f')
[7]

Recently, even more transforming-into-string functionality was added - the first argument is coerced to a string as well, e.g. j2\a\b -> "a2b"

Divisibility testing using I and GCD
Disclaimer: This only works for non-negative integers.
To check if two non-negative integers are divisible, you can do the following:
iI<divisor><dividend>

If a is divisible by b and a ≥ b ≥ 0, then gcd(a, b) = b.
It doesn't necessarily save bytes over !%<dividend><divisor>, but it might bring you a saving, because:

You might be able to tweak the implicit stuff at the end of a Pyth program (like dropping Q), when working with the dividend.
You can use it as a <pfn>, since it is a function on its own.
It handles modulo by 0.

Try it!

One more advantage: iI is a function on its own, whereas !% is not, so you can use it as a prefix function.

@EriktheOutgolfer Thanks, added to the list of advantages :)

Debugging with <newline>
If your code is written in an imperative programming style, it is quite easy to debug, since you can easily print intermediate results. (permalink)
FN.:Q2                loop
      =Y+-Y-FNhN      some random command
                Y     print intermediate result
                 ;Y   end for loop and print result

But a large amount of Pyth programs use elements of functional programming, like map, filter and reduce, which don't allow such a simple printing. But it is still possible, using the \n command.
The same code using u (reduce) would be: (permalink)
u        .:Q2Y   reduce .:Q2, start with G = Y
 +-G-FHhH        random command

If you want to print the intermediate values, simply to insert \n: (permalink)
u         .:Q2Y   reduce
   \nG             print(G)
 +-\nG-FHhH        random command

\na prints a on a newline and returns a. So you can insert it anywhere without worrying changing the functionality of the program.

You can nowadays use the newline for this, which also prints a newline.

@Pietu1998 Yes, I use it all the time. Time to update the post.

Telling if a Number is a Whole Number
A neat trick is using Invariant to tell if a number is a whole number as such:
sI

This checks if the number doesn't change when you truncate it, which it won't if it's a whole number.
For example, you can use this as a perfect square check:
sI@Q2

Use Packed Pyth
Packed Pyth is a new "programming language" which is exactly the same as Pyth, except that it uses 7 bits per character instead of 8 bits per character.
To use it, clone the pyth repository. The file packed-pyth.py is the interpreter.
Say your code is "Hello, world!.
First, put it in a file: echo -n '"Hello, world!' > code.pyth
Next, pack the Pyth code into Packed Pyth file: python3 packed-pyth.py -p code.pyth code.ppyth
Finally, run the Packed Pyth code: python3 packed-pyth.py code.ppyth
When running code, you can provide the -d flag to see what the Pyth code that's actually being run is, and you can provide input as a second command line argument after the file containing the code.
Upside:

Code is shorter by 1/8th.

Downside:

ASCII only.
No interactive input.
Full debug options are not availible.
Worse error reporting.

like we did for the safe mode thing, can we move it into a flag?

This is awesome btw :D

@Maltysen I think that would increase the byte score by one.

Can't Pyth be packed further since it only uses printable ASCII?

Assigning a variable to a function applied to itself
If you have a function of arity 1, and want to apply that to a variable and apply to itself, you can use the following syntax:
=<function><variable>

Instead of:
=<variable><function><variable>

For example, if you want to increment the variable Z, you can do:
=hZ

Which saves one byte over =ZhZ.


text:
Draw the South Korean flag
When I stumbled upon this question I remembered that I had also once seen precise rules for the construction of the South Korean flag. And this is quite a different construction.

Source: Wikipedia
So you're to draw an exact construction of this one now!
Specification
You can render the flag to file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 450x300 pixels or more.
All length ratios and positions need to be exactly as shown in the following diagram:

Source: Wikipedia
Note that the centres of the two small circles align with the diagonal.
For the colours, you must use the following palette:

White: #FFFFFF
Black: #000000
Red: #C60C30
Blue: #003478

The black boundary must not be drawn unless your drawing system does not let you specify a 3:2 canvas for technical reasons (otherwise, you should use a 3:2 canvas and the flag should fill all of it). If you do need to add the boundary, it may be arbitrarily thick - the flag should be considered strictly inside the black boundary. Any other helping lines or length indicators must not be drawn. I.e., the flag should appear exactly as in the first image.
Scoring
This is code golf, so the shortest answer (in bytes) wins.
As a word of warning, using existing compression (like embedding a compressed GIF) falls into several standard loopholes.

Interestingly, the Korean flag contains an early form of the binary number system (http://britton.disted.camosun.bc.ca/jbbinflag.htm)

Do we have to draw the border when we are using an HTML page bigger than the flag, being white there is no separation visible even if the canvas/element size is similar to the flag

@Optimizer, no, if the canvas is bounded in a way that can somehow be made visible (e.g. by the highlighting of your browser's "inspect element"), then you don't need a boundary. The black border should only be drawn in the rare case where the extent of the canvas cannot technically be defined.

I'm assuming CountryData["ROK","Flag"] doesn't count?

People Confused the South Korean Flag With the Pepsi Logo at the Winter Olympics 2018

PHP/HTML/SVG, 324
(line breaks added for legibility)
<?=gzinflate(base64_decode('tVHBioMwFPyVwF5WSOzLi/tswQjdu9cevIk1KqtriaFd9utrgpSWFva0PPImMwzDkGTz
uWXnvrl8Tj8aOPAUebLNs5Y5W33PZrKjtpOrXPOuVEy7KMiD54mKMY3yrO5tPTTMaonM9MOg32qCWgHb5Nmpch076kIih/2y
PC4jRRCIU6BhbkwGV7lmAagk3d5nCfwQdKByVBwOFLagQu6exZLNzk5fjU+B9S4u/dF1Gh/apRw6Cb83uzHm0S69/cWbSIkx
YfSf5QT6dkk5UoACIeAfXTftepb/za8='));

The compressed data expands to the same SVG data as my earlier answer shown below, but with two changes to aid compression:

The two <use> sections are expanded to the original content of the <defs> section. This makes the source text longer, but reduces the entropy so it compresses better.
In the first <g> element, I changed transform=translate(36,24)rotate(33.69) to transform=rotate(33.69)translate(43.27). This has the same effect geometrically, but compresses better because the sequence ><g transform=rotate( now appears twice.

By default, PHP will serve this as Content-Type: text/html, so the invalid XML syntax shouldn't be a problem.
SVG/HTML, 463
The HTML parser isn't too fussed about correct syntax, so we can do away with quotation marks in the parameters as long as they don't contain any spaces. It should be possible to squeeze this down further with a bit of Javascript.

<svg viewBox=0,0,72,48><defs><path d=M-25-6V6Zm3,0V6m3,0V-6M19-6V6Zm3,0V6m3,0V-6Z stroke=#000
stroke-width=2 id=p /></defs><g transform=translate(36,24)rotate(33.69)><circle r=12 fill=#c60c30
/><path d=M12,0A12,12,0,0,1-12,0A6,6,0,0,0,0,0A6,6,0,0,1,12,0Z fill=#003478 /><use xlink:href=#p
/><path d=M17,0h10z stroke=#fff stroke-width=1 /><g transform=rotate(112.62)><use xlink:href=#p
/><path d=M-27,0h4Zm6,0h4ZM20,0h4Z stroke=#fff stroke-width=1 /></g></g></svg>

Python + Pycairo, 371 370 366 bytes

from cairo import*
p=3.141593
c=Context(SVGSurface("F",12,8))
C=c.set_source_rgb;R=c.rectangle;T=c.rotate;F=c.fill
C(1,1,1);R(0,0,12,8);F()
c.translate(6,4);T(.588);b=3188
for o in[(0,.2,.47),(.77,.05,.19)]*2:C(*o);i=b/2%2;b+=1;c.arc(i,0,2-i,0,p+i*p);F();T(p)
C(0,0,0)
for x in(p,1.966)*2:
 for y in.5,0,1:
    for z in-1,1:R(3+y,-z,1./3,z*(2.75+b%2)/3);F()
    b/=2
 T(x)

Outputs a tiny SVG file named F.

C(*[.77,0,.05,.2,.19,.47][i::2]) is shorter than C(*[(.77,.05,.19),(0,.2,.47)][i%2])

Why do you write s=SVGSurface("F",12,8);c=Context(s) instead of just c=Context(SVGSurface("F",12,8))?

@IstvanChung Good point.

HTML + CSS, 966 906 843 792 762 bytes
Not a winner anytime, but lots of fun drawing in CSS. This can be golfed a lot though.
CSS, HTML:

*{position:fixed}a{background:linear-gradient(0deg,#003478 50%,#C60C30 50%);width:2in;height:2in;transform:rotate(.6rad);top:1in;left:2in}d,e{width:50%;height:50%;background:#C60C30;left:0;top:25%}a,d,e{border-radius:50%}d{background:#003478;left:50%}b,i{width:1in;height:26em;top:-1em;left:15em;transform:rotate(.98rad)}g,f,k,j{width:1in;height:17%;background:repeating-linear-gradient(0deg,#000,#000 1em,#fff 1em,#fff 1.5em);bottom:0;left:0}g,j,p{top:-.5em}b{transform:rotate(-.98rad)}c,p,v,x{height:2em;width:.5em;background:#fff;transform:rotate(.98rad)}p{top:2.8in;left:28em;transform:rotate(-.98rad) scale(1,4)}x{top:3.9em;left:28.4em}c,v{top:23.8em;transform:none}c{top:3.5em}body{height:4in;width:6in;border:1px solid
<d><e><f><g><j><k>

<x><v><c

;border:1px solid is just for show as the  tag has clear boundaries which can be observed by Inspector or similar tools, as stated by the OP
NOTE Works only in Firefox (or Chrome canary/dev) due to usage non vendor specific transforms and gradients.
See it in action

I think you should include  or
Works in Firefox 32. Fails spectacularly in Safari 7.1.

Use LESS or SASS for the CSS which should give you quite a lot of options to shorten it quite a bit. Additionally :before{content:''} and :after{content:''} are longer than just adding another element (despite this indeed looking better).

@DavidMulder I wanted the fun factor in this rather than shorter code. People can related to pure CSS more easily than LESS or SASS :)

Works in latest Chrome as well. @200_success You should be able to get it working in Safari by adding -webkit- before all the transform:s, but needless to say that would make it quite a bit longer!

Failing miserably in Chrome 38 on iOS 8.1

BBC Basic, 349 343 ASCII characters, tokenised file size 330
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
  p=1049q=25r=100VDU4118;275;-1,49,3076;19,7,-1;-1;531;255;7693;q;40;0;q,97,1200;800;29,640;400;
  FORa=38TO56STEP0.01x=r*COS(a)y=r*SIN(a)b=a*7DIV44/2IFb=3.5z=y<0ELSEz=x>0
  VDU18;1,p;-x;-y;q,153,r;0;18;2,p;x;y;q,153,r;0;18;0
  IFABS(y)DIV1=56VDUp;x*b+y;y*b-x;q;x/3;y/3;q,113,-2*y;2*x;18;7:b-=0.1VDUp;x*b+y/12;y*b-x/12;q;x/2;y/2;q,112-z,-y/6;x/6;
  NEXT

Using the correct colours added a lot, but golfing all the graphics commands down to raw VDU codes gives a saving of 6 characters overall compared with my original post. All graphics on the BBC micro is done via machine-specific ASCII control codes, so instead of using high-level graphics commands you can feed bytes direct to the VDU controller (generally shorter but at great expense to readability). A value ending in semicolon instead of comma is a 16-bit little-endian representation of 2 bytes.
Ungolfed version
  MODE16
  VDU19,1,-1,49,4,12                :REM adjust shade of red
  VDU19,7,-1,-1,-1,-1               :REM adjust shade of white to full brightness (63 is 2's complement representation of -1
  VDU19,4,-1,0,13,30                :REM adjust shade of blue
  RECTANGLEFILL40,0,1200,800        :REM plot background rectangle
  ORIGIN640,400
  FORa=38TO56STEP0.01
    x=COS(a)*100
    y=SIN(a)*100
    GCOL1:CIRCLEFILL-x,-y,100       :REM red
    GCOL4:CIRCLEFILLx,y,100         :REM blue
    GCOL0                           :REM black
    b=a*7DIV44/2                    :REM divide a by 2*(22/7) to get integer representation, then divide by 2 again.
    IFb=3.5THENz=y<0ELSEz=x>0       :REM decide whether to cut bar
    REM If the angle is correct (100*sin(a) = 56) draw bar. If required, cut out the middle of the bar.
    IFABS(INT(y))=56 MOVEx*b+y,y*b-x:MOVEBY x/3,y/3:PLOT113,-2*y,2*x:GCOL7:b-=0.1:MOVEx*b+y/12,y*b-x/12:MOVEBY x/2,y/2:IFz PLOT113,-y/6,x/6
  NEXT

At the beginning of the program I move the origin to the centre of the screen.
I don't draw any large coloured half circles. Instead I run a loop that draws small red and blue circles, spinning in an anticlockwise direction. I do nearly 3 complete revolutions (starting with blue at the right) which is obviously more than enough to fill in the disc. I stop on the 3rd revolution, just when the blue at lower right is in the correct position to line up with the bars (which have to be plotted.)
When the angle is right, I draw one of the bars. the vector x,y for drawing the current small blue circle serves to tell in which direction the bar should be. For each of the 3 revolutions, a different value of the integer a*7DIV44 is calculated, which tells whether the first, second or third bar should be drawn, with its inner edge 6/8,7/8 or 8/8 units from the centre (according to the units used in the question spec.) Because the program units are 1/4 of those in the spec, this is still a half-unit, so we divide by 2 again before saving to variable ´b´ to avoid repeated halving later.
The bars are drawn solid, then the middle is deleted if necessary. This prevents kinks from joining half-bars. The variable z indicates if a bar should be cut. That is, when y is negative for the middle bars and when x is positive for the other bars.
MOVE is an absolute move. MOVEBY is a relative move. PLOT133 considers the last two graphics cursor positions, plus the new one specified (in relative coordinates) as three corners of a parallelogram, and plots that parallelogram.
Output (& discussion of language limitations)
I selected a screen mode of 1280x800 logical pixels = 640x400 physical pixels, which by default has a black background. Onto this I draw a white rectangle from -600,-400 to 600,400 to act as my "canvas."
BBC Basic can handle 16 colours at once, from a reprogrammable pallete. But it only supports 18-bit colour, whereas the question specifies the colours as 24-bit. The colours as close as possible.

I've reworded the spec regarding the boundary a bit. The way you handled it is pretty much as I intended it.

Python 3 turtle (552 549 bytes)

(Full size image)
Edit: Now that we have Stack Snippets, here's a Stack Snippet test using Skulpt, with the help of ArtOfCode's answer here. Unfortunately, Skulpt hasn't fully implemented Python yet, so I had to mutilate half my code to get this to work. In other words, this snippet is only meant to indicate how my program works (without needing to pull up Python).
(Also, I'm finding that this might not actually work on some browsers...)

function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nimport math\nt=turtle.Turtle()\nt.speed(9)\nR="#c60c30"\nr=56.3\nk=0.6\ns=60*k\noffsetx,offsety=-215,-145\nt.up()\nt.goto(offsetx,offsety)\nt.down()\ndef q():t.rt(90)\ndef Q():t.lt(90)\ndef K():t.color("black");t.begin_fill();q()\ndef A(g,G):t.fd(g);Q();t.fd(G);Q();t.fd(g);Q();t.fd(G);Q()\ndef E():t.up();t.fd(s);t.down();Q();t.end_fill();t.up();t.fd(30*k);t.down();\ndef i():K();t.up();t.bk(s);t.down();A(120*k,20*k);E()\ndef I():K();t.up();t.fd(5*k);t.down();A(55*k,20*k);t.up();t.bk(65*k);t.down();A(55*k,20*k);E()\ndef C():t.circle(120*k,180)\nA(720*k,480*k)\nt.seth(r)\nt.up()\nt.goto(459.8*k+offsetx,173.4*k+offsety)\nt.down()\nt.color(R)\nt.begin_fill()\nC()\nt.end_fill()\nt.begin_fill()\nt.color("#003478")\nC()\nt.circle(s)\nt.end_fill()\nt.color(R)\nC()\nt.begin_fill()\nt.circle(s)\nt.end_fill()\nq()\nt.up()\nt.fd(s)\nt.down()\ni()\ni()\ni()\nt.up()\nt.bk(530*k)\nt.down()\nI()\nI()\nI()\nt.up()\nt.fd(170*k)\nt.rt(2*r)\nt.fd(180*k)\nt.down()\nI()\ni()\nI()\nt.up()\nt.bk(530*k)\nt.down()\ni()\nI()\ni()\n')}catch(a){throw Error(a.toString());}})

<canvas height="320" width="480" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>

Actual code:
import turtle as t
b=t.begin_fill
c=t.circle
e=t.end_fill
f=t.fillcolor
R="#c60c30"
r=56.3
F=t.fd
B=t.bk
s=60
def q():t.rt(90)
def Q():t.lt(90)
def K():f(0,0,0);b();q()
def A(g,G):exec("F(g);Q();F(G);Q();"*2)
def E():F(s);Q();e();F(30)
def i():K();B(s);A(120,20);E()
def I():K();F(5);A(55,20);B(65);A(55,20);E()
def C():c(120,180)
A(720,480)
t.seth(r)
t.up()
t.goto(459.8,173.4)
f(R)
b()
C()
e()
b()
f("#003478")
C()
c(s)
e()
C()
f(R)
b()
c(s)
e()
q()
F(s)
i()
i()
i()
B(530)
I()
I()
I()
F(170)
t.rt(2*r)
F(180)
I()
i()
I()
B(530)
i()
I()
i()
t.ht()

Since the turtle's such a slowpoke, if you want instant results you can add t.tracer(0) after the first line before you run the script.
Note: For some reason turtle keeps drawing what looks like extra black pixels even though I've already called up(), and I have no idea why...

I believe someone implemented Python (with turtle!) on the Stack Snippets post; if you wanted to figure out how, you could be one of the first to use this new feature! ;)

@Doorknob I had to destroy half my code to get it to even vaguely do what I wanted, but at least it visually does the same thing as in Python now. (But it doesn't work on my Chrome for some reason...)

Working fine on Chrome iOS. Glad to see someone's found a use for my project though :)

HTML + ES6, 388

<canvas id=D width=576 height=384>

If your browser supports ES6, you can view it on JSFiddle or run the snippet.
It constructs the flag out of some basic shapes, rotating the canvas first to account for the angles.

Just a note this doesn't work in Chrome 39, works fine in FF > 29.

<canvas width=576 height=384 id=D>


text:
Hungry Image Snake - Hole #3
Hole #1
Joe the snake is hungry.
He eats pictures, one pixel at a time.
He really likes bright pixels.
The Challenge
Program Joe to eat the most bright pixels he can find, given that he can only move up, down, left or right.
Specifications

Joe must start at the upper left pixel of the image.
Joe can only move horizontally or vertically by 1 each move
Joe has only enough time to move 1/3 of the amount of pixels in the picture (1/3 as many moves as pixels). If the number of pixels is not a multiple of 3, round down to the nearest integer.
Joe may cross his path, though that counts as 0 brightness
Brightness is based on the sum of r,g and b, so rgb(0,0,0) has a brightness of 0 while rgb(255,255,255) has maximum brightness.

Input
You may input the image however you like.
Output

an image showing the end result of your picture (with black being eaten pixels).
The amount of brightness eaten (please specify what range in your answer)

Scoring
Your program will be graded on:

The average brightness of pixels Joe eats
/ The average brightness of the pixels in the picture*

*you may hardcode this in your program
Your total score will be the average of the scores for the following images:
Test images:

http://upload.wikimedia.org/wikipedia/en/thumb/f/f4/The_Scream.jpg/800px-The_Scream.jpg

Fun Markdown fact - You can turn images into links to their originals: [![image description](SE URL for downsized image)](URL for original image).

It might be an idea to ask people to include an example "eaten" image in their answers.

1 image is broken: http://upload.wikimedia.org/wikipedia/en/thumb/f/f4/The_Scream.jpg/800px-The_Scream.jpg

There appears to be 804px wide image now: https://upload.wikimedia.org/wikipedia/commons/thumb/f/f4/The_Scream.jpg/804px-The_Scream.jpg

C++, Score: 1.42042 1.46766
This is essentially a slightly more sophisticated version of the two existing solutions:
Of the four possible moves, it selects the one that maximizes brightness.
However, instead of only looking at the brightness of the target pixel, it looks at the weighted sum of pixel-brightness in the neighborhood of the target pixel, where pixels closer to the target have a greater weight.
EDIT: Using nonlinear brightness in neighborhood calculation improves the score slightly.
Compile with g++ joe.cpp -ojoe -std=c++11 -O3 -lcairo. Requires cairo.
Run with joe <image-file> [<radius>].
<image-file> is the input PNG image.
<radius> (optional argument) is the radius of the summed-over neighborhood, in pixels (smaller is faster, larger is (roughly) better.)
Outputs the score and an image named out.<image-file>.
#include <cairo/cairo.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    auto* img = cairo_image_surface_create_from_png(argv[1]);
    int width = cairo_image_surface_get_width(img),
        height = cairo_image_surface_get_height(img),
        stride = cairo_image_surface_get_stride(img);
    unsigned char* data = cairo_image_surface_get_data(img);

    double* brightness = new double[width * height];
    double total_brightness = 0;
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            const unsigned char* p = data + stride * y + 4 * x;
            total_brightness += brightness[y * width + x] = p[0] + p[1] + p[2];
        }
    }

    const int r = argc > 2 ? stoi(argv[2]) : 64, R = 2 * r + 1;
    double* weight = new double[R * R];
    for (int y = -r; y <= r; ++y) {
        for (int x = -r; x <= r; ++x)
            weight[R * (y + r) + (x + r)] = 1.0 / (x*x + y*y + 1);
    }

    auto neighborhood = [&] (int x, int y) {
        double b = 0;
        int x1 = max(x - r, 0), x2 = min(x + r, width - 1);
        int y1 = max(y - r, 0), y2 = min(y + r, height - 1);
        for (int v = y1; v <= y2; ++v) {
            const double *B = brightness + width * v + x1;
            const double *W = weight + R * (v - (y - r)) + (x1 - (x - r));
            for (int u = x1; u <= x2; ++u, ++B, ++W)
                b += (*W) * (*B) * (*B);
        }
        return b;
    };

    int n = (2 * width * height + 3) / 6;
    int x = 0, y = 0;
    double path_brightness = 0;
    int O[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    for (int i = 0; i < n; ++i) {
        if (i % 1000 == 0) cerr << (200 * i + n) / (2 * n) << "%\r";

        path_brightness += brightness[width * y + x]; brightness[width * y + x] = 0;
        unsigned char* p = data + stride * y + 4 * x;
        p[0] = p[1] = 16 * i % 255; p[2] = 0;

        auto O_end = partition(begin(O), end(O), [&] (const int* o) {
            return x + o[0] >= 0 && x + o[0] < width &&
                   y + o[1] >= 0 && y + o[1] < height;
        });
        const int* o_max; double o_max_neighborhood = -1;
        for (auto o = O; o != O_end; ++o) {
            double o_neighborhood = neighborhood(x + (*o)[0], y + (*o)[1]);
            if (o_neighborhood > o_max_neighborhood)
                o_max = *o, o_max_neighborhood = o_neighborhood;
        }
        x += o_max[0]; y += o_max[1];
    }

    cout << (path_brightness * width * height) / (n * total_brightness) << endl;

    cairo_surface_write_to_png(img, (string("out.") + argv[1]).c_str());

    delete []brightness;
    delete []weight;
    cairo_surface_destroy(img);
}

Results
Bridge    1.39945
Balls     1.77714
Scream    1.38349
Fractal   1.31727
Vortex    1.66493
Tornado   1.26366
-----------------
Average   1.46766

More eye-candy

I just tried your program on some of my own sample images, and one has very much black only around the start point, and there your program crashes due to the neighbourhood lambda returning NaN.

@PlasmaHH Mind sharing the offending image?

I was feeding it vacation images... 400x400 pure black does the "trick" too though.

@PlasmaHH Well, a purely black image has an undefined score, it's zero over zero, which would be a NaN. It shouldn't affect the neighborhood calculation, though, or crash the program (though this may depend on the floating-point environment.)

Have  a look at the o_max pointer if (o_neighborhood > o_max_neighborhood)                 o_max = *o, o_max_neighborhood = o_neighborhood; only this code sets it. however due to nan involved, the comparison is always false, thus o_max is never set and used uninitialized.

@PlasmaHH That's right, but the neighborhood calculation should never result in a NaN, seeing that it only consists of multiplication and addition. When the image is completely black the NaN occurs in the final score calculation, after the loop, which is generally benign.

Python 3, score = 1.57
First our snake travels the image creating vertical lines with equal distance from each other.

We can extend this snake by taking two points next to each other in a vertical line and creating a loop whose endpoints are them.
|      |
|  =>  +----+
|      +----+
|      |

We organize the points into pairs and for every pair we store the size and average brightness value of the loop which gives has the greatest average brightness.
At every step we choose the pair with highest value extend its loop to achieve maximum average brightness on the extension and calculate the new optimal loop size and brightness value for the pair.
We store the (value,size,point_pair) triplets in a heap structure sorted by value so we can remove the biggest element (in O(1)) and add the new modified one (in O(log n)) efficiently.
We stop when we reachg the pixel count limit and that snake will be the final snake.
The distance between the vertical lines has very little effect in the results so a constant 40 pixel was choosen.
Results
swirl    1.33084397946
chaos    1.76585674741
fractal  1.49085737611
bridge   1.42603926741
balls    1.92235115238
scream   1.48603818637
----------------------
average  1.57033111819

Note: the original "The Scream" picture was not available so I used an other "The Scream" picture with similar resolution.
Gif showing the snake extending process on the "swirl" image:

The code takes one (or more space separated) filename(s) from stdin and writes the resulting snake images to png files and prints the scores to stdout.
from PIL import Image
import numpy as np
import heapq as hq

def upd_sp(p,st):
    vs,c=0,0
    mv,mp=-1,0
    for i in range(st,gap):
        if p[1]+i<h:
            vs+=v[p[0],p[1]+i]+v[p[0]+1,p[1]+i]
            c+=2
            if vs/c>mv:
                mv=vs/c
                mp=i
    return (-mv,mp)

mrl=[]
bf=input().split()

for bfe in bf:
    mr,mg=0,0
    for gap in range(40,90,1500):

        im=Image.open(bfe)
        im_d=np.asarray(im).astype(int)

        v=im_d[:,:,0]+im_d[:,:,1]+im_d[:,:,2]

        w,h=v.shape

        fp=[]
        sp=[]
        x,y=0,0
        d=1

        go=True
        while go:
            if 0<=x+2*d<w:
                fp+=[(x,y)]
                fp+=[(x+d,y)]
                sp+=[(x-(d<0),y)]
                x+=2*d
                continue
            if y+gap<h:
                for k in range(gap):
                    fp+=[(x,y+k)]
                y+=gap
                d=-d
                continue
            go=False

        sh=[]
        px=im.load()

        pl=[]

        for p in fp:
            pl+=[v[p[0],p[1]]]
            px[p[1],p[0]]=(0,127,0)

        for p in sp:
            mv,mp=upd_sp(p,1)
            if mv<=0:
                hq.heappush(sh,(mv,1,mp+1,p))

        empty=False
        pleft=h*w//3
        pleft-=len(fp)
        while pleft>gap*2 and not empty:

            if len(sh)>0:
                es,eb,ee,p=hq.heappop(sh)
            else:
                empty=True
            pleft-=(ee-eb)*2

            mv,mp=upd_sp(p,ee)
            if mv<=0:
                hq.heappush(sh,(mv,ee,mp+1,p))

            for o in range(eb,ee):
                pl+=[v[p[0],p[1]+o]]
                pl+=[v[p[0]+1,p[1]+o]]
                px[p[1]+o,p[0]]=(0,127,0)
                px[p[1]+o,p[0]+1]=(0,127,0)

        pl+=[0]*pleft

        sb=sum(pl)/len(pl)
        ob=np.sum(v)/(h*w)

        im.save(bfe[:-4]+'snaked.png')

        if sb/ob>mr:
            mr=sb/ob
            mg=gap

    print(bfe,mr)
    mrl+=[mr]

print(sum(mrl)/len(mrl))

Python 2 (score: 0.0797116)
Just a very simple and naïve greedy algorithm to get the ball rolling.
#!/usr/bin/python

from PIL import Image

OFFSETS = [(-1, 0), (0, -1), (1, 0), (0, 1)]
def test_img(filename):
    img = Image.open(filename)

    joe, eaten = (0, 0), []
    img_w, img_h = img.size
    all_pixels = [
        sum(img.getpixel((x, y)))
        for x in xrange(img_w)
        for y in xrange(img_h)
    ]
    total_brightness = float(sum(all_pixels)) / len(all_pixels)

    for _ in xrange(0, (img_w*img_h)/3):
        max_offset, max_brightness = (0, 0), 0
        for o in OFFSETS:
            try:
                brightness = sum(img.getpixel((joe[0] + o[0], joe[1] + o[1])))
            except IndexError:
                brightness = -1
            if brightness >= max_brightness:
                max_offset = o
                max_brightness = brightness

        joe = (joe[0] + max_offset[0], joe[1] + max_offset[1])
        eaten.append(max_brightness)
        img.putpixel(joe, (0, 0, 0))

    eaten_brightness = float(sum(eaten)) / len(eaten)
    print('%d of %d (score %f)' % (eaten_brightness, total_brightness, eaten_brightness / total_brightness))
    img.show()

test_img('img0.jpg')
test_img('img1.png')
test_img('img2.jpg')
test_img('img3.jpg')
test_img('img4.jpg')

Output:
llama@llama:~/Code/python/ppcg40069hungrysnake$ ./hungrysnake.py
15 of 260 (score 0.060699)
9 of 132 (score 0.074200)
16 of 300 (score 0.055557)
4 of 369 (score 0.010836)
79 of 400 (score 0.197266)

I think your scoring is off. It is the average of Joe's brightness eaten over the average brightness for the whole picture... A random Joe should get a score of roughly 1.

@StretchManiac Hmm, I don't see anything wrong. sum of brightnesses of eaten pixels / amount of eaten pixels is the right formula, correct? Maybe it's just a really terrible algorithm ;)

@Doorknob it is The average brightness of pixels Joe eats / The average brightness of the pixels in the picture*

For the orange and black swirly (not blue) one, I got an average brightness of 68.0846... Which doesn't seem to match any of yours. Perhaps sum(getPixel(...)) doesn't return what you want? (I'm kinda a python newbie). BTW, there are 6 pictures, but you only have 5 outputs. Could you also label the pictures somehow?

@StretchManiac How are you calculating your brightness? Mine just sums the R, G, and B values. Sorry, I missed the swirly one that comes second-to-last (the one you mentioned in your comment, I think). I'll add that in the morning (I have to sleep now).

That's the same as I calculated mine. Here is my code if you are interested.

@Doorknob Your snake might be getting stuck in the corners of the images.  My algorithm appears to be very similar to yours, and that was a problem I ran into.  To remedy it, I randomize which surrounding pixel is chosen in the case of a tie, in order to prevent a bias toward a specific direction that could eventually lead to the snake getting trapped in the corner.

Java (score: 0.6949)
A simple algorithm which eats the brightest pixel out of the four pixels surrounding the current pixel.  In the case of a tie, the pixel eaten is random, leading to differing scores and resulting images each execution.  As such, the scores below are the averages over 50 executions on each image.
To run it, either edit the three arguments (existing as class constants) in the source, or pass them via command line in the form java HungryImageSnake <source> <iterations> <printScores> where <source> is the source file of the image to eat, <iterations> is the number of times to eat the image (taking the average score and saving the best score over all iterations), and <printScores> is true to print each iteration's score or false to not.
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class HungryImageSnake {

    private static final String SOURCE = "tornado.jpg";
    private static final int ITERATIONS = 50;
    private static final boolean PRINT_SCORES = true;

    public static void main(String[] args) {
        try {
            String source = args.length > 0 ? args[0] : SOURCE;
            int iterations = args.length > 1 ? Integer.parseInt(args[1]) : ITERATIONS;
            boolean printScores = args.length > 2 ? Boolean.parseBoolean(args[2]) : PRINT_SCORES;

            System.out.printf("Reading '%s'...%n", source);
            System.out.printf("Performing %d meals...%n", iterations);
            BufferedImage image = ImageIO.read(new File(source));
            double totalScore = 0;
            double bestScore = 0;
            BufferedImage bestImage = null;
            for (int i = 0; i < iterations; i++) {
                HungryImageSnake snake = new HungryImageSnake(image);
                while (snake.isHungry()) {
                    snake.eat();
                }
                double score = snake.getScore();
                if (printScores) {
                    System.out.printf("    %d: score of %.4f%n", i + 1, score);
                }
                totalScore += score;
                if (bestImage == null || score > bestScore) {
                    bestScore = score;
                    bestImage = snake.getImage();
                }
            }
            System.out.printf("Average score: %.4f%n", totalScore / iterations);
            String formattedScore = String.format("%.4f", bestScore);
            String output = source.replaceFirst("^(.*?)(\\.[^.]+)?$", "$1-b" + formattedScore + "$2");
            ImageIO.write(bestImage, source.substring(source.lastIndexOf('.') + 1), new File(output));
            System.out.printf("Wrote best image (score: %s) to '%s'.%n", bestScore, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int x;
    private int y;
    private int movesLeft;
    private int maximumMoves;
    private double eatenAverageBrightness;
    private double originalAverageBrightness;
    private BufferedImage image;

    public HungryImageSnake(BufferedImage image) {
        this.image = copyImage(image);
        int size = image.getWidth() * image.getHeight();
        this.maximumMoves = size / 3;
        this.movesLeft = this.maximumMoves;
        int totalBrightness = 0;
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                totalBrightness += getBrightnessAt(x, y);
            }
        }
        this.originalAverageBrightness = totalBrightness / (double) size;
    }

    public BufferedImage getImage() {
        return image;
    }

    public double getEatenAverageBrightness() {
        return eatenAverageBrightness;
    }

    public double getOriginalAverageBrightness() {
        return originalAverageBrightness;
    }

    public double getScore() {
        return eatenAverageBrightness / originalAverageBrightness;
    }

    public boolean isHungry() {
        return movesLeft > 0;
    }

    public void eat() {
        if (!isHungry()) {
            return;
        }
        int[][] options = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        shuffleArray(options); // prevent snake from getting stuck in corners
        int[] bestOption = null;
        int bestBrightness = 0;
        for (int[] option : options) {
            int optionX = this.x + option[0];
            int optionY = this.y + option[1];
            if (exists(optionX, optionY)) {
                int brightness = getBrightnessAt(optionX, optionY);
                if (bestOption == null || brightness > bestBrightness) {
                    bestOption = new int[]{ optionX, optionY };
                    bestBrightness = brightness;
                }
            }
        }

        image.setRGB(bestOption[0], bestOption[1], 0);
        this.movesLeft--;
        this.x = bestOption[0];
        this.y = bestOption[1];
        this.eatenAverageBrightness += bestBrightness / (double) maximumMoves;
    }

    private boolean exists(int x, int y) {
        return x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight();
    }

    private int getBrightnessAt(int x, int y) {
        int rgb = image.getRGB(x, y);
        int r = (rgb >> 16) & 0xFF;
        int g = (rgb >> 8) & 0xFF;
        int b = rgb & 0xFF;
        return r + g + b;
    }

    private static <T> void shuffleArray(T[] array) {
        Random random = new Random();
        for (int i = array.length - 1; i > 0; i--) {
            int index = random.nextInt(i + 1);
            T temp = array[index];
            array[index] = array[i];
            array[i] = temp;
        }
    }

    private static BufferedImage copyImage(BufferedImage source){
        BufferedImage b = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
        Graphics g = b.getGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
        return b;
    }
}

Average scores, by image, over fifty iterations:
Bridge - 0.7739
Spheres - 0.5580
Scream - 0.8197
Fractal - 0.3850
Vortex - 0.9158
Tornado - 0.7172

Best scores, by image, over the same fifty iterations:
Bridge - 0.8996
Spheres - 0.8741
Scream - 0.9183
Fractal - 0.5720
Vortex - 1.1520
Tornado - 0.9281

The highest scoring runs' images:

As is evident from the images, far less than a third of the pixels are actually eaten, as the snake occasionally gets stuck among pixels it has already eaten, at which it remains stuck within the dead area until the randomness of its movements bring it to an edible portion of the image.
Also as a result of the snake re-eating pixels, the scores are biased downward, as the zero-brightness of the dead pixels is again factored into the average. I would expect to see far higher scores if the scoring algorithm was modified to only divide by the number of moves that led to eating new pixels, rather than all moves (including those where the snake eats a now-dead pixel that it has eaten before).
Of course, a better approach would be to create some sort of brightness heuristic for each pixel and find the path of width * height / 3 pixels with the highest average brightness, but I doubt this approach will be optimal in run time, especially on larger images, as the number of possible permutations would be very large.  I may take a shot at some form of this approach later and post it in a separate answer if so.

If anyone is bothered by how large my answer is (due to the images in it), let me know and I'll remove the images in favor of links or another less-spacy alternative.  Or, if anyone would like the full resolution originals of any "eaten" images, let me know in a comment as well.

Python 2, Score: 1.205
I put together a quick Python solution some time ago but forgot to post it. Here it is. It finds the richest blocks in the image, then travels to each block, eating all the best blocks it comes to.
Results
bridge.jpg: 591.97866/515.41501 =                               1.14855
BallsRender.png: 493.24711/387.80635 =                          1.27189
Mandel_zoom_04_seehorse_tail.jpg: 792.23990/624.60579 =         1.26838
Red_Vortex_Apophysis_Fractal_Flame.jpg: 368.26121/323.08463 =   1.13983
The_Scream.jpg: 687.18565/555.05221 =                           1.23806
swirl.jpg: 762.89469/655.73767 =                                1.16341

AVERAGE                                                         1.205

Example Picture

Python 2.7 Code
from pygame.locals import *
import pygame, sys, random

fn = sys.argv[1]

screen = pygame.display.set_mode((1900,1000))
pic = pygame.image.load(fn)
pic.convert()
W,H = pic.get_size()
enough = W*H/3
screen.blit(pic, (0,0))

ORTH = [(-1,0), (1,0), (0,-1), (0,1)]
def orth(p):
    return [(p[0]+dx, p[1]+dy) for dx,dy in ORTH]

def look(p):
    x,y = p
    if 0 <= x < W and 0 <= y < H:
        return sum(pic.get_at(p))
    else:
        return -1

# index picture
locs = [(x,y) for x in range(W) for y in range(H)]
grid = dict( (p,sum(pic.get_at(p))) for p in locs )
rank = sorted( grid.values() )
median = rank[ len(rank)/2 ]
dark = dict( (k,v) for k,v in grid if v < median )
good = dict( (k,v) for k,v in grid if v > median )
pictotal = sum(rank)
picavg = 1.0 * pictotal/(W*H)
print('Indexed')

# compute zone values:
block = 16
xblocks, yblocks = (W-1)/block, (H-1)/block
zones = dict( ((zx,zy),0) for zx in range(xblocks) for zy in range(yblocks) )
for x,y in locs:
    div = (x/block, y/block)
    if div in zones:
        colsum = sum( pic.get_at((x,y)) )
        zones[div] += colsum

# choose best zones:
zonelist = sorted( (v,k) for k,v in zones.items() )
cut = int(xblocks * yblocks * 0.33)
bestzones = dict( (k,v) for v,k in zonelist[-cut:] )

# make segment paths:
segdrop = [(0,1)] * (block-1)
segpass = [(1,0)] * block
segloop = [(0,-1)] * (block-1) + [(1,0)] + [(0,1)] * (block-1)
segeat = ( segloop+[(1,0)] ) * (block/2)
segshort = [(1,0)] * 2 + ( segloop+[(1,0)] ) * (block/2 - 1)

def segtopath(path, seg, xdir):
    for dx,dy in seg:
        x,y = path[-1]
        newloc = (x+dx*xdir, y+dy)
        path.append(newloc)

# design good path:
xdir = 1
path = [(0,0)]
segtopath(path, segdrop, xdir)
shortzone = True
while True:
    x,y = path[-1]
    zone = (x/block, y/block)
    if zone in bestzones:
        if shortzone:
            seg = segshort
        else:
            seg = segeat
    else:
        seg = segpass
    segtopath(path, seg, xdir)
    shortzone = False
    # check end of x block run:
    x,y = path[-1]
    zone = (x/block, y/block)
    if not ( 0 <= x < xblocks*block ):
        del path[-1]
        segtopath(path, segdrop, xdir)
        shortzone = True
        xdir = xdir * -1
    if len(path) > enough:
        break
print('Path Found')

# show path on picture:
loc = path.pop(0)
eaten = 1
joetotal = grid[loc]
i = 0
while eaten <= enough:
    loc = path[i]
    i += 1
    pic.set_at(loc, (0,0,0))
    joetotal += grid[loc]
    eaten += 1
    if i % 1000 == 0:
        screen.blit(pic, (0,0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == QUIT: sys.exit(0)

# save picture and wait:
screen.blit(pic, (0,0))
pygame.display.flip()
pygame.image.save(pic, 'output/'+fn)
joeavg = 1.0 * joetotal/eaten
print '%s: %7.5f/%7.5f = %7.5f' % (fn, joeavg, picavg, joeavg/picavg)
while True:
    for event in pygame.event.get():
        if event.type == QUIT: sys.exit(0)