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.
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 :)
I'm trying to write a code that would add the total of all the values from 0 to 100 and printing only the total after computing with any loop structure.
For another one I did it was short so I did this
def listsum(numList):
iSum = 0
for i in numList:
iSum = iSum + i
return iSum
print(listsum([1,2,3,4,5,6,7,8,9,10]))
but 0 to 100 is too much ,, is there another way?
Use a range:
print(listsum(list(range(101))))
Using range:
def listsum(numList):
iSum = 0
for i in range(1, numList+1):
iSum += i
return iSum
You would just pass the max value that you want the count up to (e.g. print(listsum(100))).
The built-in sum() function gives the total value of all numbers in a list, so your listsum() function is not needed.
list(range(101)) gives you a list of all numbers from 1-100 (inclusive)
Putting those together you get
print(sum(list(range(101))))
Which adds the total of all the values from 0 to 100
The range function is much more powerful than this, here's a good reference for using it it's something you really need to know how to use well!
Currently taking a programming course and got as an assignment to find the first fibonacci number above a million and I'm having a bit of trouble finding the specific number. I'm also supposed to be finding the index of the n:th number when it hits 1 million. I'm pretty new to coding but this is what I've come up with so far, just having a hard time to figure out how to actually calculate what the number is.
I guess you would switch out the for-with a while-loop but haven't figured out it how to get it all to work.
Thanks in beforehand :)
def fib_seq(n):
if n <= 2:
return 1
return fib_seq(n-1) + fib_seq(n-2)
lst = []
for i in range(1, 20):
lst.append(i)
print(fib_seq(i), lst)
Some points:
You don't need to build a list. You're only asked to return an index and the corresponding Fibonnacci number.
The recursive algorithm for Fibonnacci is not best practice, unless you would use some memoization. Otherwise the same numbers have to be recalculated over and over again. Use an iterative method instead.
Here is how that could look:
def fib(atleast):
a = 0
b = 1
i = 1
while b < atleast:
a, b = b, a+b
i += 1
return i, b
print(fib(1000000)) # (31, 1346269)
If you need to do this with some find of recursion, you should try to avoid calling the recursions twice with each iteration. This is a classic example where the complexity explodes. One way to do this is to memoize the already calculated results. Another is to maintain state with the function arguments. For example this will deliver the answer and only call the function 32 times:
def findIndex(v, prev = 0, current = 1, index = 0):
if v < prev:
return (prev, index)
return findIndex(v, current, prev+current, index + 1 )
findIndex(1000000) # (1346269, 31)
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.
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.