def pearson_chi_squared_test(observed=[], expected=[], df=None, tail=UPPER):
 o = list(observed)
 e = (list(expected) or _expected(o))
 n = len(o)
 m = (len(o[0]) if o else 0)
 df = (df or ((n - 1) * (m - 1)))
 df = (df or (((m == 1) and (n - 1)) or (m - 1)))
 x2 = 0.0
 for i in xrange(n):
  for j in xrange(m):
   if ((o[i][j] != 0) and (e[i][j] != 0)):
    x2 += (((o[i][j] - e[i][j]) ** 2.0) / e[i][j])
 p = gammai((df * 0.5), (x2 * 0.5), tail)
 return (x2, p)

def pearson_chi_squared_test ( observed = [ ] , expected = [ ] , df = None , tail = UPPER ) : o = list ( observed ) e = ( list ( expected ) or _expected ( o ) ) n = len ( o ) m = ( len ( o [ 0 ] ) if o else 0 ) df = ( df or ( ( n - 1 ) * ( m - 1 ) ) ) df = ( df or ( ( ( m == 1 ) and ( n - 1 ) ) or ( m - 1 ) ) ) x2 = 0.0 for i in xrange ( n ) : for j in xrange ( m ) : if ( ( o [ i ] [ j ] != 0 ) and ( e [ i ] [ j ] != 0 ) ) : x2 += ( ( ( o [ i ] [ j ] - e [ i ] [ j ] ) ** 2.0 ) / e [ i ] [ j ] ) p = gammai ( ( df * 0.5 ) , ( x2 * 0.5 ) , tail ) return ( x2 , p )
returns for the n x m observed and expected data .