This question already has answers here:
calculating catalan numbers using memoization
(2 answers)
Closed 7 years ago.
I am trying to use memoization in order to calculate catalan numbers, but it just does not seem to work, what do I need to change?
def catalan_mem(n, mem = None):
if n==0:
return 1
if mem==None:
mem={}
sum=0
if n not in mem:
for i in range(0, n):
sum = sum + catalan_mem(i) * catalan_mem(n-i-1)
mem[n]=sum
return mem[n]
You need to pass the cache to your recursive calls:
sum = sum + catalan_mem(i, mem) * catalan_mem(n-i-1, mem)
Otherwise, every method call creates a new empty cache.
Related
This question already has answers here:
How can I clamp (clip, restrict) a number to some range?
(9 answers)
Closed 4 years ago.
i have a simple problem in Python where i need to return a value that is equal to floor if it is smaller than floor, and return ceiling if the value is larger than ceiling. I'm not sure if there is a simpler way to do so. What i will do is:
def floor_ceil(x):
floor = 0
ceil = 100
if x < floor:
return floor
elif x > ceil:
return ceil
return x
Are there simpler ways to do so? The code looks clunky
You could reuse the built-in max and min:
def floor_ceil(x):
return max(0, min(100, x))
This question already has answers here:
How to find cube root using Python? [duplicate]
(3 answers)
Closed 6 years ago.
I saw this post recently, about getting square roots in python: How to calc square root in python?
I have used the sqrt(x) command, but I don't know how to make it work for cube roots and anything higher than that.
Also, I'm using Python 3.5.2.
Any help on this?
In Python, you may find floating cube root by:
>>> def get_cube_root(num):
... return num ** (1. / 3)
...
>>> get_cube_root(27)
3.0
In case you want more generic approach to find nth root, you may use below code which is based on Newton's method:
# NOTE: You may use this function only for integer numbers
# k is num, n is the 'n' in nth root
def iroot(k, n):
u, s = n, n+1
while u < s:
s = u
t = (k-1) * s + n // pow(s, k-1)
u = t // k
return s
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I would like to determine if the factorial of n raised to the same power is larger or the factorial of (n raised to the power n).
Here's my Python code.
def whichIsLarger():
def fact(n):
assert type(n) == int
if n == 0 or n == 1:
return 1
else:
return n * fact(n-1)
print max( fact(n**n), fact(n)**fact(n) )
Will this code execute correctly (i.e. without yeilding any semantic errors)?
Is there any way of testing this code without assigning any particular value to the variable n?
I mean I would like Python to do a general (i.e. a mathematical or algebraic osrt of) comparison for me, not just the usual arithmetical one that assigning the value 8, for example, to the integer n would effect.
Is there any built-in function in Python for computing factorials?
What is the difference if we write the factorial function inside or outside of the whichIsLarger function?
You'll probably want to look at the maths for something that's gonna blow up like that. Doing it naively will mean your code will take ages to execute and you'll be repeating lots of stuff if n starts getting large. If you can get a relationship between n-1 and n you may find you can clear a lot of the work
Nonetheless, here is naive code to get you started, but you will want to try and simplify it if you can
def factorial(n):
if n == 1:
return 1
return n *factorial(n-1)
def func1(n):
return factorial(n)**(factorial(n))
def func2(n):
return factorial(n**n)
for i in range(1, 5):
val1 = func1(i)
val2 = func2(i)
if val1 > val2:
print "func1 is larger: " + str(val1)
elif val2 > val1:
print "func2 is larger: " + str(val2)
else:
print "equal"
EDIT
Recursion sucks, especially on python, go with:
def factorial(n):
x = 1
for i in range(1,n+1):
x = x*i
return x
from math import factorial
def first_equation(n):
nf = factorial(n)
return nf ** nf
def second_equation(n):
return factorial(n ** n)
but you will very soon find that the numbers get insanely huge, you spend a long time waiting, and it really doesn't prove much because you might get a different result for really big n.
Instead you need to approach it symbolically. I suggest using Stirling's approximation - as n -> +inf, n! -> (n/e)**n * (2pi * n)**0.5
Another approach is to use the sympy symbolic math package:
import sympy as sp
# if you want LaTeX output, ie in iPython notebook
sp.init_printing(use_latex=True)
n = sp.symbols("n")
first_equation = sp.factorial(n) ** sp.factorial(n)
second_equation = sp.factorial(n ** n)
You can then use the equations directly, like
for n_val in range(7):
fen = first_equation .evalf(subs={"n":n_val})
sen = second_equation.evalf(subs={"n":n_val})
print(n_val, fen, sen)
which produces
0 1.00000000000000 1.00000000000000
1 1.00000000000000 1.00000000000000
2 4.00000000000000 24.0000000000000
3 46656.0000000000 1.08888694504184e+28
4 1.33373577685028e+33 8.57817775342843e+506
5 3.17504237378034e+249 2.41317228491761e+9566
6 1.90281878633202e+2057 6.89642755739806e+197572
or symbolically, like
# find the limit as n -> +infinity
relation = first_equation / second_equation
limit = sp.limit(relation, n, sp.oo)
print("Limit of eq1/eq2 as n -> +inf is {}.".format(limit))
which produces
Limit of eq1/eq2 as n -> +inf is 0.
(that is, (n**n)! will become infinitely larger than n! ** n!.)
This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 7 years ago.
I'm attempting to calculate e^x using recursion, e^x = e^(x/2)*e^(x/2), and the third order Maclaurin expansion for e^x and the script keeps returning 1. I'm not looking for a higher accuracy solution, just simply to understand where the script goes wrong : )
My thought is that with enough iterations it should end up with (1+x/N+(x/N)^2/2)^N when the function value goes below the limit.
def exp(x):
if abs(x)<0.0001:
return 1+x+x**2/2
else:
y=exp(x/2)
return y*y
Try this instead (note the 2.0 in the recursive call):
def exp(x):
if abs(x) < 0.0001:
return 1 + x + x**2 / 2.0
else:
y = exp(x / 2.0)
return y * y
It is failing because if you pass an integer in for x, say 1, then x / 2 does integer division (in python 2.x), which would result in 0 instead of 0.5. By using x / 2.0, it forces python to use float division.
def exp(x):
if abs(x)<0.0001:
return 1+x+(x**2)/2.0
else:
y=exp(x/2.0)
return y*y
Integer division truncates. You need floats here.
This question already has answers here:
How to define a decimal class holding 1000 digits in python?
(4 answers)
Closed 7 years ago.
please go easy on me, I've been learning Python about a week!
I thought I'd try calculating Pi using the Rumanujan formula. I am confident I was able to code that correctly.
My answer is truncating and I'd like it to be represented with 200 dp. In C I'd use malloc to do this perhaps but I understand that Python doesn't work that way.
The learning point I'd like to take away from this is: Is the truncation caused by the limit of representing a float, and if so is it possible to fix?
Thanks.
import math
from decimal import *
getcontext().prec = 200
def iterate(n):
sum = 0
Decimal(sum)
sum = (math.factorial(4*n))
sum = (sum/math.pow(math.factorial(n), 4))
sum = sum*((26390*n +1103)/math.pow(396, (4*n)))
return sum
ans=0
Decimal(ans)
print "Choose the number of iterations:\n"
itnum = int(raw_input())
for n in range (0, itnum+1):
this_iteration = 0
Decimal(this_iteration)
this_iteration = iterate(n)
ans = ans + this_iteration
ans = ans*(math.pow(8, 0.5)/9801)
ans = 1/ans
print "%.200f" % ans
Your snippet
sum = 0
Decimal(sum)
leaves sum set to the int 0, and computes and throws away a Decimal equivalent. Use, instead, an assignment statement:
sum = Decimal(0)
Next, you'll need to ensure every intermediate result is also converted appropriately to Decimal (and floats by default are not).
Personally, I'd recommend using gmpy2 instead, but then, I'm biased:-).