Python

Reading from standard in

 * Read all input from standard in and store it in a string (29 bytes):

import sys
s=sys.stdin.read()

 * A shorter way that is almost always better (26 bytes):

import os
s=os.read(0,1e5)

 * As above but the input has fewer than 100 bytes: use a smaller number as the parameter (25 bytes):

import os
s=os.read(0,99)

Example: reverse entire input : Solution

 * Read a single line (without the carriage return) and store it in a string (13 bytes):

s=raw_input()

 * Read all input from standard in and store it in an array with one element per line, including the carriage return (34 bytes):

import sys
a=sys.stdin.readlines()

 * As above but without the carriage return (38 bytes):

import os
a=os.read(0,1e5).split('\n')

 * If the lines contain no whitespace except the newline at the end (34 bytes):

import os
a=os.read(0,1e5).split()

Notice that if you need to read fewer than 100 bytes, again you can use 99 instead of 1e5.

 * Read only two lines from standard in (without the carriage return) and store then in an array of strings (21 bytes):

r=raw_input
a=r(),r()

 * Iterate over the lines (is this supported in all versions of Python?):

import sys
for s in sys.stdin:0

 * Iterate over the lines (without carriage returns), but it causes an exception when the input runs out:

while 1:s=raw_input()

 * Iterate over the lines (without the carriage returns) then do something once the iteration has finished (35 bytes):

try:
 while 1:s=raw_input()
except:0

 * Read an integer (or any valid Python expression) from standard in (9 bytes):

i=input()

 * Read a space separated list of integers (30 bytes):

a=map(int,raw_input().split())

Writing to standard out


 * Output a string or an integer (7 bytes):

print s

 * Append a space instead of a newline after the output (8 bytes):

print s,

Note that the space is not added if the next print is with no arguments.

 * Output an array of strings, one per line (17 bytes):

print'\n'.join(a)


[TODO: Insert example of using input() and raw_input() to print]

Example: join lines : Solution

Embedding raw binary data

You can embed raw bytes into your program by putting them in a string, and read them back by indexing into the string and using the ord function to convert characters to integers between 0 and 255. There are a few special characters that need escaping:

* If the binary string contains chr(10), escape it using \n.
* For chr(13) use \r.
* For chr(0), you can use \0 unless the next character is an octal digit, in which case you must use \000.
* If your binary data contains a single-quote chr(39), surround the string using double-quotes.
* Similarly, if your binary data contains a double-quote chr(34), surround the string using single-quotes.
* If there are both single-quotes and double-quotes, you can surround the string using double quotes and escape internal double-quotes using \". Alternatively you can do the same using single-quotes.
* Backslashes = chr(47) need to be escaped only when followed by one of the characters in the following list:

\n " ' 0 1 2 3 4 5 6 7 \ a b f n r t v x

or at the end of the string. If this is the case, replace the backslash with a double backslash.

Finally, if you are using Python 2.5 or above and there are any bytes greater than or equal to 128 in your binary data, you will need to add an encoding to the beginning of the file. This can be done in just three bytes using the UTF-8 byte order mark \xef \xbb \xbf. If you forget the byte order mark, you will get something like the following error:

SyntaxError: Non-ASCII character '\xee' in file program.py on line 4, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

Other Python tricks

* Simulating C's ternary operator (p?a:b):

r=[b,a][p]

This method always evaluates both a and b, so it cannot be used if you require short-circuiting behaviour. If you require short-circuiting:

r=p and a or b

This method can fail if 'a' might evaluate to False in a boolean context. The following always works, but requires Python 2.5:

r=a if p else b

Special cases:

If a is any string and b="" (or a is any integer and b=0):

r=a*p

If a is any integer and b=1:

r=a**p

If a and b are both integers:

r=b+(a-b)*p

 * Ending the program when a term becomes zero by dividing by zero:

while 1:
 # Calculate the value of i
 1/i # Exit if i is zero.
 # Do something with i

This is a useful trick when you need to abort the program midway through the loop.

Example: count down : Solution


 * Loop using exec instead of "for i in range(9):f()":

exec"f();"*9

Example: Twin primes : Solution


 * Combine multiple conditionals. Instead of "1<x and x<2":

1<x<2

Example: Rule 30 : Solution


 * Generate a small random integer.

Use id on an obect and then use % to restrict the result to a small subset of the integers. The value will be different for each execution of the program. The function id always returns values that are divisible by 4, so avoid using 2 or 4 as the modulus.

id('')%5

Example: 123 : Solution


Other tricks: TODO: explain these in more detail, give examples.

 * tab/space: two levels of indenting
 * ~- and -~ for -1 and +1 to change the precedence
 * << and >> for multiplication and division, to change the precedence
 * os.read() to read n bytes at a time in a loop
 * [::-1] to reverse a string or list
 * using zlib to compress data
 * find instead of index on strings
 * import a,b and from a import*
 * Omitting the space in "1if"
 * List comprehensions/generators. Nesting.

Comments