multiplication - Python does not follow order of PEMDAS? -


i programming catalan number generator homework, , doing recursive program in pytohon.

the program:

def catalan(n):     if n == 0:         c_f = 1     else:         c_f = ((4*n-2)/(n+1))*catalan(n-1)     return c_f  print catalan(10) 

returns 5832, wrong answer, but

def catalan(n):     if n == 0:         c_f = 1     else:         c_f = (4*n-2)*catalan(n-1)/(n+1)     return c_f  print catalan(10) 

gives me 16796, correct answer.

so python not follow pemdas?

just pemdas, python evaluates expressions left right. evaluates (4*n-2)/(n+1), stores (call result x), , computes x/catalan(n-1).

the problem is, value of x? (4*n-2)/(n+1) not integer values of n, if you're passing in value of n python int you're performing integer division. result fractional part of computation discarded, , computation goes off rails.

the second iteration works because of property of catalan function (4*n-2)*catalan(n-1) expression multiple of n-1. way, leave (potentially destructive) division end of expression, , mathematical properties of computation save you.


Comments