Programming
Python 

powered by FreeFind

Modified: 

Overview

Any language can be used for AI programming but, because finding a solution to an AI problem often requires exploration and experimentation, it is wise to use a language that is powerful and can be quickly written and modified. The more abstract (higher-level from the machine) generally the better; we wouldn't normally write AI in assembly or C++ until after a solution was found and greater efficiency required.

Python is a simple but powerful language that comes with many of the fundamental tools (recursion, classes, lists, tuples) needed for quickly programming AI applications. It will be the language of choice for most course assignments.

Getting Started

Interactive mode

Python can be entered one statement at a time in IDLE shell window; useful for learning the language and debugging. Enter:

Editing and running programs

The editor is used to edit files and run Python programs.

def factorial(n) :
     if n <= 1 : return 1
     return n*factorial(n-1)

b = 16

 

Try creating a new file
  • Open Python.
  • In IDLE shell click: File | New Window
  • Copy and Paste the above program.
  • Click: File | Save | test.py
  • Click:
    • Run | Run Module
    • b
    • factorial( 5 )

Debugging in interactive mode

Interactive mode makes debugging programs much simpler (a dynamic debugger is part of the IDLE Shell). After running the module (i.e. Run Module) global variables can be examined and functions called.

Restarting - Restart a Python program by closing the Shell and running the module again.

Examining variables -  Examine the global table variable by entering:

table

Calling functions - Call the TABLE_DRIVEN_AGENT function with actual parameter of
 (A, 'Dirty') by:

TABLE_DRIVEN_AGENT( (A, 'Dirty') )

Try
  • Download and save the TABLE-DRIVEN-AGENT of Figure 2.7 as f2-7.py
  • In IDLE shell click: File | Open | f2-7.py
  • Run by clicking:
    • Run | Run Module
    • Call the run() function by: run()
  • Debug by:
    • Examine variable table.
    • Call function TABLE_DRIVEN_AGENT( (A, 'Dirty') )

TABLE-DRIVEN-AGENT (Figure 2.7)

#   Figure 2.7 page 45

A='A'
B='B'
percepts = []        
table = {((A, 'Clean'),): 'Right',    # [Fig. 2.3]
             ((A, 'Dirty'),): 'Suck',
             ((B, 'Clean'),): 'Left',
             ((B, 'Dirty'),): 'Suck',
             ((A, 'Clean'), (A, 'Clean')): 'Right',
             ((A, 'Clean'), (A, 'Dirty')): 'Suck',
             # ...
             ((A, 'Clean'), (A, 'Clean'), (A, 'Clean')): 'Right',
             ((A, 'Clean'), (A, 'Clean'), (A, 'Dirty')): 'Suck',
             # ...
          }
def LOOKUP(percepts, table):           # Lookup appropriate action for percepts
    action = table.get(tuple(percepts))
    return action 
def TABLE_DRIVEN_AGENT(percept): # Determine action based on table and percepts
    percepts.append(percept)            # Add percept 
    action = LOOKUP(percepts, table) # Lookup appropriate action for percepts
    return action
def run() :                                      # run agent on several percepts
    print 'Action\tPercepts'
    print TABLE_DRIVEN_AGENT((A, 'Clean')),'\t', percepts
    print TABLE_DRIVEN_AGENT((A, 'Dirty')),'\t', percepts
    print TABLE_DRIVEN_AGENT((B, 'Clean')),'\t', percepts

Programming

Data types

Python is provides very flexible data types useful for AI:

Try
  • Lists - A universal data type that can be heterogeneous; for example:   
    • L = [12, 'A', ['a nested list'], 3.14 ]
    • L[2]
    • L.append('another')

     

  • Tuples - Similar to a C struc; used to group related data; represents heterogeneous data;  example:
    • T = ('A', [1,2,3])
    • T[1]
    • percept = (('A','Clean'), ('B','Dirty'))
    • (x, y) =  (('A','Clean'), ('B','Dirty'))
    • x
    • z = x + y
    • z
    • ( (a, b), (c, d) ) =  (('A','Clean'), ('B','Dirty'))
    • a
    • d

     

  • Dictionary - An associative array; consists of keys and value pairs; example:
    • D = { 'C463' : 'AI', 'a list':[1,2,3], ('A', 'Clean'):5 }
    • D['C463']
    • D['a list']
    • D[('A', 'Clean')]

Variables (dynamically typed)

Variables are dynamically typed by the value to which it is bound. In the program:

Try
  1. Run p7-2.py
  2. Use the string concatenation operator on A, a string:
    • A=A+'1234'
    • A
  3. Bind L to a list and perform some list operations:

    • L = [4, 'Hi', ('A', 'Clean')]

    • L

    • L[2]

    • L.append('cow')

    • L

    • L.append(['a list', ['a nested list']])

    • L

  4.  Attempt to use string concatenation on lists:

    • A = A + L

Indentation

Used instead of { } to specify scope.

Control statements

Similar to C++.

x = 4
if x<5 :
    print 'x<5'
    x+=1
else
    print 'x>=y'

Scope (static)

Any identifier defined outside a function is global; inside local.

Functions

Similar to C++. The factorial function; notice the indentation:

def factorial(n) :
    if n <= 1 :
        return 1
    return factorial(n-1)*n

Try

Write the power function for xn where n is a positive integer.

  • Click File | New Window
  • Click File | Save | power.py
  • Type the function.
  • Click Run | Run Shell | OK to save
  • In Shell enter: power(4,3)