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.
Related
This is for a school assignment.
I have been tasked to define a function determining the largest square pyramidal number up to a given integer(argument). For some background, these are square pyramidal numbers:
1 = 1^2
5 = 1^2+2^2
14 = 1^2+2^2+3^2
So for a function and parameter largest_square_pyramidal_num(15), the function should return 14, because that's the largest number within the domain of the argument.
I get the idea. And here's my code:
def largest_square_pyramidal_num(n):
sum = 0
i = 0
while sum < n:
sum += i**2
i += 1
return sum
Logically to me, it seemed nice and rosy until I realised it doesn't stop when it's supposed to. When n = 15, sum = 14, sum < n, so the code adds one more round of i**2, and n is exceeded. I've been cracking my head over how to stop the iteration before the condition sum < n turns false, including an attempt at break and continue:
def largest_square_pyramidal_num(n):
sum = 0
for i in range(n+1):
sum += i**2
if sum >= n:
break
else:
continue
return sum
Only to realise it doesn't make any difference.
Can someone give me any advice? Where is my logical lapse? Greatly appreciated!
You can do the following:
def largest_pyr(x):
pyr=[sum([i**2 for i in range(1,k+1)]) for k in range(int(x**0.5)+1)]
pyr=[i for i in pyr if i<=x]
return pyr[-1]
>>>largest_pyr(15)
14
>>> largest_pyr(150)
140
>>> largest_pyr(1500)
1496
>>> largest_pyr(15000)
14910
>>> largest_pyr(150000)
149226
Let me start by saying that continue in the second code piece is redundant. This instruction is used for scenario when you don't want the code in for loop to continue but rather to start a new iteration (in your case there are not more instructions in the loop body).
For example, let's print every number from 1 to 100, but skip those ending with 0:
for i in range(1, 100 + 1):
if i % 10 != 0:
print(i)
for i in range(1, 100 + 1):
if i % 10 == 0:
# i don't want to continue executing the body of for loop,
# get me to the next iteration
continue
print(i)
The first example is to accept all "good" numbers while the second is rather to exclude the "bad" numbers. IMHO, continue is a good way to get rid of some "unnecessary" elements in the container rather than writing an if (your code inside if becomes extra-indented, which worsens readability for bigger functions).
As for your first piece, let's think about it for a while. You while loop terminates when the piramid number is greater or equal than n. And that is not what you really want (yes, you may end up with a piramid number which is equal to n, but it is not always the case).
What I like to suggest is to generate a pyramid number until in exceedes n and then take a step back by removing an extra term:
def largest_square_pyramidal_num(n):
result = 0
i = 0
while result <= n:
i += 1
result += i**2
result -= i ** 2
return result
2 things to note:
don't use sum as a name for the variable (it might confuse people with built-in sum() function)
I swapped increment and result updating in the loop body (such that i is up-to-date when the while loop terminates)
So the function reads like this: keep adding terms until we take too much and go 1 step back.
Hope that makes some sense.
Cheers :)
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.
I have an array A = [1 - 100] and I need to find the sum of all the two digit values in this array. How would I approach this? I have tried :
def solution(A):
A =array[0-100])
while A > 9 & A < 99
total = sum(A)
print "%s" % total
)
Is there a function that given an array consisting of N integers returns the sum of all two digit numbers i.e A = [1,1000,80, -91] the function should return -11(as the two are 80 and -91). not a range, multiple array
You can use a list comprehension and check if the length of the string-format is equal to 2, like so:
sum([x if len(str(x))==2 else 0 for x in xrange(1,101)])
Use the keyword and rather than the bitwise &.
Edit: a fuller answer, as that's not the only thing wrong:
def solution():
A = range(101)
total = sum([a for a in A if 9 < a <= 99])
print total
This uses list comprehension and chained inequalities, so is pretty 'pythonic'.
There is tons of errors in your code, please next time before posting,spend some time try to figure it out yourself and be sure that your code at lest doesn't contain any obvious syntax error.
By array, I assume you're talking about a list. And change it to range(101) for every number from 0 to 100
def solution(A):
return sum([x for x in range(A) if len(str(abs(x))) == 2])
print(solution(101))
As a side note, use and instead of & since that's a bitwise-or sign.
Here are a couple of ways to go about the problem, the first is most similar to the approach you appear to be trying:
def solution1(array):
total = 0
for a in array:
if 9 < a < 100:
total += a
return total
print(solution1(range(101)))
And here's a more compact solution using a comprehension (actually, a generator expression):
def solution2(array):
return sum(a for a in array if 9 < a < 100)
print(solution2(range(101)))
Note that in your original you're confusing loops and conditionals.
Create a function addNumbers(x) that takes a number as an argument and adds all the integers between 1 and the number (inclusive) and returns the total number.
Examples :
addNumbers(10)
55
addNumbers(1)
1
So this is a question, I have done using while loop , and it worked fine. But I am not satisfied with my code, I also did this problem using for loop and that's okay for me, but I want to know what could be the best way to improve dis code using while loop.
def addNumbers(num):
total = 1
i = 1
while i < num:
i += 1
total += i
return total
print addNumbers(10)
And here is my for loop answer :
def addNumbers(num):
my_list = list(range(num+1) )
for i in my_list:
my_list.append(i)
return sum(my_list)
If you want an O(1) algorithm that isn't brute-force, you can use Gauss's method:
def sum_numbers(n):
return (n+1)*n//2
Usually SO isn't the place for such questions, but anyway..
You can use sum() and range(). range() will return a list of numbers from 0 to n and sum will, well, sum it.
def sumNumbers(n):
return sum(range(n+1))
EDIT: And using while loop:
def sumNumbers(n):
i = 0
sum = 0
while i <= n:
sum += i
i += 1
return sum
Make use of numpy's sum routine and a generator like so,
import numpy as np
maxNumber = 10
sumOfNumbers = np.sum([(x) for x in xrange(1, maxNumber+1)])
print sumOfNumbers
The generator gives you the list of numbers & the routine adds them for you.
so if the function is:
function(n)
what can i do to if i want.
function(5)
to return as
1
2
3
4
5
I'm thinking towards creating an empty list, but i don't know what to append into the list to get the number 1 up to 'n'
You can try
def function(n):
for x in range(0, n):
print x+1
if you want to print the values, or
def function(n):
returnlist = []
for x in range(0, n):
returnlist.append(x+1)
return returnlist
to return a list.
The for x in range(0, n): part of the code is called a for loop. It repeats itself n times, and x is incremented by one each time is repeats. You can then use x to accomplish different tasks within your code. In this case, we're simply taking its value plus one and printing it or appending it to a list. We have to add one to the value because x is zero based, although it doesn't have to be. We could just as easily have written for x in range(1, n+1): and not have had to add one to the x value.
Here is a simple example:
def function(n):
for i in range(1, n+1):
print i