As a new python programmer, I'm working on a Leetcode question and don't know why my code does not work, so I really appreciate your advice:
Question:
Implement pow(x, n), which calculates x raised to the power n.
Example:
Input: 2.00000, 10
Output: 1024.00000
Here is my python code (I tried to use divide and conquer concept):
class Solution:
def myPow(self, x, n):
if n == 0:
return 0
if n == 1:
return x
return self.power(x,n)
def power(self,x,n):
if n == 1:
return x
self.power(x,n//2)
self.multiply(x,x)
return x
def multiply(self,x,y):
x = x*y
return x
test3=Solution()
test3.myPow(2,4)
But the results give 2 instead of 16. I expect the above code to work as follows:
power(2,4)->power(2,2)->power(2,1), which reaches the base case since n==1, and then we proceed with power(2,2),due to function multiply(x,x) or multiply(2,2) in this case, I expect x to become 4 (x = 2*2), and then we proceed with power(2,4), due to function multiply(x,x), x = 4*4 = 16
I don't know why I am wrong, could any expert give me some advice?
x^0 always equals 1, so your first "if" in myPow() is not accurate.
Also, your power() function always returns x, because the lines:
self.power(x,n//2)
self.multiply(x,x)
don't assign the value they return to anything.
class Solution:
def myPow(self, x, n):
if n == 0:
return 1
if n == 1:
return x
return self.power(x,n)
def power(self,x,n):
if n == 1:
return x
x = self.power(x,n//2)
return self.multiply(x,x)
def multiply(self,x,y):
x = x*y
return x
test3=Solution()
test3.myPow(2,4)
This code only fixes some minor problems in your code, but still you should consider cases when the power n is an odd number.
You aren't storing the return values from your self.power() and self.multiply() within power().
This is due to function scope. When you change x within multiply(), it is only changed within that function. You are correctly returning the changed value but you don't store it in the calling function.
Changing power() to the following works for your example (2^4).
def power(self,x,n):
if n == 1:
return x
x = self.power(x,n//2)
x = self.multiply(x,x)
return x
However, your algorithm is flawed as 2^3 returns 4 rather than 8.
First, I would note that x ^ 0 = 1, but your code states that it should equal zero within your first if statement within myPow. Second, your big problem is that you are not storing any of your intermediate results. Within the power function, you have:
def power(self,x,n):
if n == 1:
return x
self.power(x,n//2)
self.multiply(x,x)
return x
This function is taking in x and n, then computing subproblems using these variables, and then returning the original x. Therefore, in your example, calling test3.power(x, y) will always return the original x value. Instead, do the following.
def power(self,x,n):
if n == 1:
return x
# Account for when n is not even.
n1 = n // 2
n2 = n - n1
# Calculate powers.
x1 = self.power(x, n1)
x2 = self.power(x, n2)
# Combine divide-and-conquer answers and return.
x = self.multiply(x,x)
return x
Also notice that I changed the function to break the problem into powers of n1 and n2. This is because your function would not correctly handle something like power(2, 3). In this case, the original function would compute power(2, 3 // 2) = power(2, 1) which is not what you want. I hope this helps.
Related
I have been kinda practicing some recursive / dynamic programming exercises, but I have been struggling trying to convert this recursive problem into a top-down one, as for example, for f(4,4), the recursive one yields 5, whereas my top-down yields 2.
I can see the base cases being the same, so I might be messing up with the logic somehow, but I haven't found where.
the code is as written:
def funct(n, m):
if n == 0:
return 1
if m == 0 or n < 0:
return 0
return funct(n-m, m) + funct(n, m-1)
and the top-down approach is:
def funct_top_down(n, m):
if n == 0:
return 1
if m == 0 or n < 0:
return 0
memo = [[-1 for x in range(m+1)] for y in range(n+1)]
return funct_top_down_imp(n, m, memo)
def funct_top_down_imp(n, m, memo):
if memo[n][m] == -1:
if n == 0:
memo[n][m] = 1
elif m == 0 or n < 0:
memo[n][m] = 0
else:
memo[n][m] = funct_top_down_imp(n-m, m, memo) + funct_top_down_imp(n, m-1, memo)
return memo[n][m]
Thanks!
The basic idea is to compute all possible values of func instead of just one. Sounds like a lot, but since func needs all previous values anyways, this would be actually the same amount of work.
We place computed values in a matrix N+1 x M+1 for given N, M so that it holds that
matrix[n][m] === func(n, m)
Observe that the first row of the matrix will be all 1, since f(0,m) returns 1 for every m. Then, starting from the second row, compute the values left to right using your recursive dependency:
matrix[n][m] = matrix[n-m][m] + matrix[n][m-1]
(don't forget to check the bounds!)
Upon completion, your answer will be in the bottom right corner of the matrix. Good luck!
Write a function named powPosInt. This function will take two integer input parameters, named x and p. This function will compute the value of x to the power of p, where p >= 0, which is defined as x to the power of p = x × · · · × x
| {z }
p times
or 1 if p is 0.
The function will return this computed result. This function should not produce any console output.
For computing x to the power of p
, I am requiring that you implement the calculations using a while loop and an accumulator variable.
Examples of values you should test with: x = 2, p = 3 should return 8. x = 1, p = 4
should return 1. x = 7, p = 0 should return 1. x = −3, p = 2 should return 9.
x = −3, p = 3 should return −27.
This is what I have so far, I am having trouble figuring out how to put a while loop within this function. I am asking on here for help as my TEACHER will not assist, (he wants us to treat his class like the real world where we will have to figure out solutions on our own... why pay his salary right?)
def powPosInt(x,p):
number = p
count = 0
while (number != 0):
answer = (x**p)
count = count + 1
if (p<0):
answer = (x**(1/abs(p)))
return answer
Using accumulation means you need to create a variable that will store the result, and while loop will multiply it by x each step. You shouldn't use the ** operator.
steps = 0
result = 1
while (steps < p):
result *= x
steps += 1
def powPosInt(x,p):
number = p
count = 0
while (number != 0):
answer = (x**p)
count = count + 1
if (p<0):
answer = (x**(1/abs(p)))
return answer
I see a number of problems here:
A loop for calculating powers will be using repeated multiplication, not exponentiation. The intent here is to assume Python doesn't have an exponentiation operator, otherwise this assignment would be futile.
There's no reason to handle negative powers, the specifications clarly call for p >= 0. Hence your final if block is unnecessary.
This is a style issue only: you should get into the habit of using meaningful variable names. The only situation in which I use single-letter variables nowadays is a short-lived, non-nested, loop where the variable name is irrelevant (and I use i for that). For any other situation, I use explanatory names (yes, not even j or k for nested loops). And I'm even starting to move away from using i for these simple cases.
Having said all that, I'd suggest revisiting your solution to take those into account.
Once you've done so, you can refer to the code below for one solution:
def powPosInt(myBase, myPower):
result = 1
for _ in range(myPower):
result *= myBase
return result
And, if you wanted to go for extra credits(a), you could put in place contractual checks to ensure callers are doing the right thing:
def powPosInt(myBase, myPower):
if type(myBase) != int: raise TypeError("Base must be an integer")
if type(myPower) != int: raise TypeError("Power must be an integer")
if myPower < 1: raise ValueError("Power must be >= 1")
result = 1
for _ in range(myPower):
result *= myBase
return result
(a) Or risk losing marks for being a smart-alec. This depends very much on the personality of your teacher :-)
I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.
f(x) represents the function of a triangular waveform. In which you input the value x and it returns you the associated y value. However my function returns x every time instead of y. For example f(1) should give 2/pi instead of 1.
def f(x):
y=x
if x in arange(-math.pi,-math.pi/2):
y=(-2/math.pi)*x-2
elif x in arange(-math.pi/2,math.pi/2):
y=(2/math.pi)*x
elif x in arange(math.pi/2,math.pi):
y=(-2/math.pi)*x+2
return y
numpy.arange returns an array of non-consecutive numbers. in operation against it will return True only if the left-hand operand belong to those numbers.
You'd better to use <= / < pair to avoid such problem. In addition to be correct, it also save cost of creating arrays.
def f(x):
y = x
if -math.pi <= x < -math.pi/2:
y = (-2/math.pi)*x-2
elif -math.pi/2 <= x < math.pi/2:
y = (2/math.pi)*x
elif math.pi/2 <= x < math.pi:
y = (-2/math.pi)*x+2
return y
The 'in' keyword only checks if the searched element lies in the list. Here, your list contains only values in the step of 1. Perhaps the value of x is not an integral step. Hence, the corrected function would be:
def f(x):
y=x
if x>-math.pi and x<-math.pi/2:
y=(-2/math.pi)*x-2
elif x>-math.pi/2 and x<math.pi/2:
y=(2/math.pi)*x
elif x>math.pi/2 and x<math.pi:
y=(-2/math.pi)*x+2
return y
I am trying to create a function in Python. This function should be able to create a list of whole numbers less than or equal to the number provided. I've created an empty list, a variable called y and a while loop. In this while loop, as long as y <= x, the results of the subsequent equations are appended to the empty list, and y increments by 1. However, when I call this function, I get a list with only one element. How can I fix this?
def fff(x):
numbers = []
y = 2
while(y <= x):
x = x - (x - y)
numbers.append(x)
y += 1
return numbers
>>> fff(10)
[2]
That function already exists, more or less.
Python 2
def fff(x):
return range(1,x+1)
Python 3
def fff(x):
return list(range(1,x+1))
If you look at this line x = x - (x - y) and think of your inputs, you will see the problem. if x initially equals 10, then x - (x - y) equals 2, and y will equal 3, therefore breaking out of your loop.
If you are trying to mimic the range function then this is how you would do it:
def fff(x):
numbers = []
y = 1
while(y <= x):
numbers.append(y)
y += 1
return numbers