Getting Started with Python
Python is a high level programming language. It uses indentation for block delimiters. Python has two currently active versions: 2.7.x and 3.2.x. Version 3 is not backwards compatible with version 2. (There are some tricks you can do to make code run with both versions, but for the contest, you should pick one or the other.)
Python is pre-installed on most Linux distributions and on Mac OSX, but you probably need to upgrade. Windows does not come with Python.
- Download the latest version from the Python site.
- Select the windows installer for either version 2.7.2 or 3.2.2. Select the X86-64 version if you have a 64-bit computer.
- Run the installer and select all the defaults. You should have the python executable at C:Python27python.exe or C:Python32python.exe
- Add C:Python27 or C:Python32 to your path.
Test your installation at the command line and make sure you have 2.7.x or 3.2.x:
python --version
Check current version
python --version
Install or upgrade
Ubuntu:
sudo apt-get install python
or:
sudo apt-get install python3
Check current version
python --version
Install or upgrade
Download the Mac OSX python .dmg file. Open up the file and drag the program to your applications folder.
Now that Python is installed, you should be able to run play_one_game.cmd and test_bot.cmd successfully. Continue reading if you want to program your bot in Python.
Interactive Mode
You can try running Python interactively to practice proper syntax:
C:\>python Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> dir(math) ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cos h', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfin ite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] >>> math.e ** (0j * math.pi) (1+0j) >>> "python"[2:-1] 'tho' >>> [x**2 for x in range(20) if x % 2 == 0] [0, 4, 16, 36, 64, 100, 144, 196, 256, 324] >>> def division(dividend, divisor): ... return dividend//divisor, dividend%divisor ... >>> quotient, remainder = division(17,5) >>> print(quotient, remainder) 3 2 >>> print("{0} remainder {1}".format(*division(37,7))) 5 remainder 2 >>> import os >>> os.getcwd() 'C:\\' >>> import antigravity >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'antigravity', 'division', 'math', 'os', 'quotient', 'remainder'] >>> quit()
Python Program
Let's create a python program to produce prime numbers using the Sieve of Eratosthenes:
C:\>notepad prime.py
Contents:
import argparse from math import sqrt, floor def primes(n): sieve = {x: True for x in range(2, n)} for num in range(2, floor(sqrt(n))): for multiple in range(num ** 2, n, num): sieve[multiple] = False return [x for x, is_prime in sieve.items() if is_prime] def main(): parser = argparse.ArgumentParser(description='List prime numbers.') parser.add_argument('--max', type=int, default=100, help='highest prime number to generate') args = parser.parse_args() print(' '.join(map(str, primes(args.max + 1)))) if __name__ == '__main__': main()
Run the program with:
python prime.py --max 1337
At the top, we imported some helper functions. Argparse is what we use to add the --max
command line option to the program. The other imports are math functions that we import directly into the main namespace. The next block of code is our sieve function. It returns a list of prime numbers up to a given maximum. The third block of code is our main function. It parses the command line options, then calls our prime number function and prints the out the result. The last line of code is a guard to prevent any code from executing if we imported our program into another one. It will only run the main function if it is being executed directly from the command line.
If you don't understand everything in this program, it is worth studying the individual functions and keywords until you do: import/from...import, def, dictionary comprehensions, range, for...in, floor, sqrt, return, list comprehensions, argparse, print, join, map, str.
Performace and testing
We can test the performance of our prime program with the following:
python -m cProfile prime.py --max 3021377
This will output a large list of function calls and their timings. The profile will become useful if you want to make your bot as fast as possible. It will help identify the slowest parts of your program that you need to focus on. If you run a game with playgame.py and specify the -I
option, you should get an input file that you can then redirect into your bot program:
python -m cProfile MyBot.py < game_lots\0.bot0.input
We can use our program interactively as well:
C:\>python Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import prime >>> dir(prime) ['__builtins__', '__cached__', '__doc__', '__file__', '__name__', '__package__', 'argparse', 'floor', 'main', 'primes', 'sqrt'] >>> prime.primes(10) [2, 3, 5, 7, 9] >>> quit()
The dir()
function tells us everything that is in the prime
namespace that we imported. You can see our own functions along with the other function we imported.
Now that you are familiar with Python, you should head over to the Ants Tutorial