a = int(input("please give the number which refer to x0: "))
b = int(input("please give the number which refer to m: "))
pw = 1
c = a
fc = a
temp = a
res = 0
for i in range(2, b + 1, 1):
while i > 0:
pw = pw * a
if c > 1:
fc = fc * (c - 1)
c = c - 1
i = i - 1
temp = temp + 1
c = temp
res = pw / fc + res
fc = temp
pw = 1
print(res + a + 1)
I think your solution looks pretty good and so easy to understand. This is my computer lab exam question and we mustn’t use any library and also power operator(**) in this exam. I wan’t to share my solution. Thanks for your reply
I’m guessing you could use built-in libraries, but if you can’t use this:
def _compute(x, m):
_x = sum(
(x if i == 0 else x * term[-1]) / (factorial := 1 if j == 0 else factorial * j)
for i, term in enumerate([[1] for _ in range(m)])
for j in range(i + 1)
)
return _x
Well if no imports can be used, we can improve some part of @Sky ’s program
To
def _compute(x, m):
result = 1
last_factorial = 1
last_exponent = 1
for i in range(m):
result += (last_exponent / last_factorial)
last_factorial *= i
last_exponent *= x
return result
I also improved the performance by a bit by saving the last factorial&exponent and multiply them with a new one instead of re-calculating factorials&exponents
And it kept it’s simplicity compared to the later solution given by @Sky
However, if m is the precision of the calculation. From what I remembered, m greater than a number below 30 (I forgot the exact number) will not be more accurate. This is because there is a limit for how many digits after decimal point is allowed in float variables. If m need to be large, the package Decimal have to be used for better precision, without import I don’t think it could work.
My code is more optimized since it uses a single loop structure and avoids repetitive calculations by using a single expression to compute the sum. So, I am willing to sacrifice a bit of readability just to get that extra optimization.