from math import log, exp, pow class Solution: def __init__(self): """ The constructor exists only to initialize variables. You do not need to change it. """ self.evals=0 self.tolerance=0.000001 #Set the tolerance for computing b def computeB(self,S,N): """ Entry point for recursive computeB function """ '''You need to set these to reasonable values''' upperBound= log(S,N) lowerBound= 1.000000 lowerBound, upperBound = self.computeB_R(lowerBound,upperBound,S,N) return (lowerBound+upperBound)/2 def computeB_R(self,lowerBound,upperBound,S,N): '''check stopping condition for recusion, stop on else''' if(upperBound-lowerBound) > self.tolerance: '''compute mean''' guess=(upperBound+lowerBound)/2 '''compute the expression using guess as b ''' val= 0.000000 for x in range(1,N+1): val += pow(guess,x) '''figure out if guess was too high or too low''' if(val>=S): '''return a call to yourself with apprpriately changed bounds''' return self.computeB_R(lowerBound,guess,S,N) else: '''return a call to yourself with apprpriately changed bounds''' return self.computeB_R(guess,upperBound,S,N) else: return lowerBound,upperBound if __name__ == "__main__" : s=Solution() '''This is roughly what the grader does''' print("Testing 13 = b + b^2 + b^3 + b^4") ans=s.computeB(13,4) if( (ans - 1.5326593400551733) < 0.000001): print("Yay, computeB(13,4) works!!") else: print("There seems to be something wrong with you script.") '''Testing Result - based on the euqatino this should add up to 13''' print("This should add up to 13: " , ans + ans**2 + ans**3 + ans**4) ''' Note, since b is taken to large powers, the result can be sensitive. For large number computing b to 6 digital places might not be enough to get the exact value back. '''
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question