Reputation: 259
I have the following Python equation:
def E(r, b):
if r == 0:
return 0
elif b == 0:
return r
else:
return max(0, (r/(r+b))*[1+E(r-1,b)]+(b/(r+b))*[E(r,b-1)-1])
print E(1,1)
The recursion does not seem to work. For E(1, 1) the mathematical equation should return 1/2. However I am getting 0. And for E(2, 2), I am getting an error, when mathematically it should be 2/3.
from __future__ import division
def E(r, b):
if r == 0:
return 0
elif b == 0:
return r
else:
return max(0, (float(r)/float(r+b))*[1+E(r-1,b)]+(float(b)/float(r+b))*[E(r,b-1)-1])
print E(1,1)
I made the following adjustments but still ran into errors: "TypeError: can't multiply sequence by non-int of type 'float'"
Upvotes: 0
Views: 65
Reputation: 21
The problem is as best as I can tell that you are using ints where you want to use floats, also I'm guessing that you are using the square brackets as an alternative to using two parenthesis in a row. Python is interpreting the square brackets as a list and when you multiply a list by an int python will return a list with that many repetitions of the list
['a', 'b'] * 5
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
When you tried to multiply the list by a float python can't handle it and just returns a type error. It looks like if you just change the ints to floats and replace the square brackets with parens you should be good.
def E(r, b):
r = float(r)
b = float(b)
if r == 0:
return 0
elif b == 0:
return r
else:
return max(0, (r/(r+b))*(1+E(r-1,b))+(b/(r+b))*(E(r,b-1)-1))
print E(1,1)
Upvotes: 1
Reputation: 39287
For Python 2, When you substitute r = 1 and b = 1, the front part of the equation becomes:
1 / (1+1) = 0
So the max
will always return max(0, 0)
@Alik mentions from __future__ import division
if you need floating point division
>>> from __future__ import division
>>> def E(r, b):
... if r == 0:
... return 0
... elif b == 0:
... return r
... else:
... return max(0, (r/(r+b))*(1+E(r-1,b))+(b/(r+b))*(E(r,b-1)-1))
...
>>> print (E(1,1))
0.5
>>> print (E(2,2))
0.666666666667
>>>
Upvotes: 3