I want to define a function, sumAll(n) that sums all numbers from 1 to n.
For example, when I call sumAll(10) should return the answer 55...
Because:
1+2+3+4+5+6+7+8+9+10 = 55
The function sumAll needs to use a for loop to carry out this summation, and it will have to use a sum variable that increases in value over each iteration of the for loop.
I have a working function that does not use a for loop, but I need to know how to use a for loop to accomplish this as well.
Here is the working program:
def sumAll(n):
if n == 0:
return 0
return n + sumAll(n - 1)
number = int(raw_input("Please enter a number: \n"))
print ("The answer is: ") + str(sumAll(number))
How do I use a "for" loop to accomplish this?
Am I right in assuming the "for loop" should be nested in the "sumAll" function?
I have tried many times to do this using a for loop and I keep getting a infinite result and errors...
Here is my code:
def sumAll(n):
y = n + sumAll(n -1)
return y
num = int(raw_input("Please enter a number")
for n in range(num):
num = sumAll(num)
print num
By for loop
def sumAll(n):
sum_all = 0
for i in range(1, n+1):
sum_all = sum_all + i
return sum_all
number = int(raw_input("Please enter a number: \n"))
print ("The answer is: ") + str(sumAll(number))
Output:
Please enter a number:
10
The answer is: 55
You can also use list Comprehension:
print sum([i for i in range(number+1)])
Output:
55
You can also use a mathematical series formula:
def sumAll(n):
return n * (n + 1) / 2
you can even do it without a loop:
def sumAll(n):
return sum(range(1,n+1))
print(sumAll(10)) # -> 55
if you insist on using a loop:
def sumAll(n):
s = 0
for i in range(1,n+1):
s += i
return s
but the mathematical solution is simply:
def sumAll(n):
return n * (n + 1) / 2
# in python 3:
# return n * (n + 1) // 2
(there are n elements with an average value of (n+1)/2; this will always be an integer since either n or n+1 is even; the proof by induction is often the first example when math students learn about induction...).
You will get an error with sum(1, 2, 3, 4)
TypeError: sum expected at most 2 arguments, got 4
sum((1, 2, 3, 4)) # works cuz tuple inside
sum([1, 2, 3, 4]) # works cuz list inside
so the func will need to gather elements into a tuple, e.g.
numbers = 1, 2, 3, 4
print(sum(numbers)) # already a tuple so works
use * with your parameter to gather the caller's args into a tuple.
* enabbles any-number of args to be supplied by caller and they are converted into a tuple parameter.
def sumall(*args):
return sum(args)
print(sumall(1))
print(sumall(1, 2))
print(sumall(1, 2, 3))
print(sumall(1, 2, 3, 4))
produces the expected answers. Credit: author Downey asks for this exercises solution in chapter 12 of Think Python (2016)
Related
Trying to divide multiple numbers in a for loop, output is incorrect answer
Created a variable for the answer, in each for loop it will make answer equal to the previous loops answer divided by the integer from the for loops list.
def div(x):
ans = 0
for i in x:
ans = ans / int(i)
b = int(input("How many numbers would you like to " + opt + "?"))
c = range(0,b)
d = list()
for i in c:
d.append(input("What number would you like to " + opt + "?"))
print(div(d))
If 3 numbers are input to the list (d). I want to divide these 3 numbers and make the variable (ans) equal to the quotient
Example:
Input 3 numbers - 200, 10, 2
Result: 10
Actual Results from script: 0.0
You have two problems:
First, our function does not return a value. You can fix this by adding return ans at the end of the function.
Second, if you start with ans = 0, dividing ans will only get you more zeros.
Here's one solutions, using a placeholder to skip over the solution:
def div(x):
ans = None
for i in x:
if ans is None:
ans = i
else:
ans = ans / int(i)
return ans
Here's a slightly more elegant alternative, using an arbitrary argument list.
def div(init, *divisors):
ans = init
for x in divisors:
ans /= x # divide and assign together
return ans
div(100, 10, 2) # returns 5
div(*[100, 10, 2]) # returns 5
By declaring a function parameter with *, any extra parameters given will be packed into it as a list. You can then pass arguments to it without putting them in a list, or you can use another * to unpack the list into multiple arguments.
The div function doesn't actually return anything, so it should be printing None ?
this should fix your problem:
def div(x):
ans = 0
for i in x:
ans = ans / i
return ans
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
M = M + 1
print(sum)
This is my python code, every time I run the program, it prints the number twice. (1 1 4 4 9 9 etc.) Just confused on why this happening - in intro to computer programming so any help is appreciated (dumbed down help)
My guess is the print statement is not indented inside the if statement properly. As the sum wont increase for an even number and every other number is even
Make sure you have everything indented properly
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
print(sum)
M = M + 1
My best bet would be to add M++ line after the scope of if statement.
What really is happening that your increment only works when it is inside the if statement but this is logically incorrect because it should increment everytime loop executes.
Get rid of eval() you really do not need it. and replace it with int(). By default input() is a string by default so int() converts it to an integer.
You are using a reserved keyword sum
Try running sum.__doc__. You will see that sum is actually an inbuilt function. You should not create a variable the same name as an inbuilt function. However you can use an underscore (described in pep8) and this will create a working variable.
Corrected code:
M = int(input("Input the first number "))
N = int(input("Input the second number(greater than M) "))
sum_ = 0
while M <= N:
if M % 2 == 1:
sum_ = sum_ + M
M = M + 1
print(sum_)
I am trying to code a function. The function accepts two parameters, k and n. It should return the sum of the k-th powers of the numbers from 1 to n.
For example, sumPowerN(1, 3) should return 6
The answer for the above example is 6 because 1^1 + 2^1 + 3^1 = 6
This is what I've done so far;
def sumPowerN(k,n):
result = 0
for n in range(1, n+1, n):
result = result + (1 ** k) + (2 ** k) + (n ** k)
return result
def main():
print("Program to calculate sum of k-th powers of numbers from 1 to n")
kVal, nVal = input("Please enter the k-th value and the n-th value (k,n): ")
answer = sumPowerN(kVal, nVal)
print("The value of the sum is:", answer ,".")
main()
Please help. I am really stuck. And please do point out what I'm doing wrong because I am still new to Python.
def sumPowerN(k,n):
result = 0
for n in range(1, n+1):
result = result + (n ** k)
return result
def main():
print("Program to calculate sum of k-th powers of numbers from 1 to n")
kVal, nVal = input("Please enter the k-th value and the n-th value (k,n): ")
answer = sumPowerN(kVal, nVal)
print("The value of the sum is:", answer ,".")
main()
resulted in:
$ python sumPowerN_Cg.py
Program to calculate sum of k-th powers of numbers from 1 to n
Please enter the k-th value and the n-th value (k,n): 1,3
('The value of the sum is:', 6, '.')
You don't need to keep adding the 1 and 2 powers; just use the fact that range will give you the entire list of bases to be raised.
def sum_power_n(k, n):
result = 0
for i in range(1, n+1):
result += i**k
return result
Fucntional approach:
import operator
import itertools
def sumPowerN(k,n):
return sum(itertools.imap(lambda x:operator.pow(x, k), xrange(1, n+1)))
sumPowerN(1,3)
6
Here is a pretty simple example of what I mean:
def work():
x = input("Give me a number : ")
if x in range(30000):
print "hello"
So as long as I put in a number in that range it will print hello, but what if I want it to only accept an odd number in that range? I tried defining a separate function that's range is only odd numbers like this:
def work():
a = input("Give me a number : ")
if a in range(30000):
X = range(30001)
y = (2*X)-1
if a in range(y):
print "hello"
but that doesn't work.
if 0 <= x < 30000 and x % 2 == 1:
print "hello"
Note: Python 2.x didn't do the optimisation - so this only applies to Python 3.x's range
You can take advantage that xrange (or range in 3.x - needn't generate the list and can do membership testing...) by providing it with a step parameter as well as the start and end stops...
So, you could use to check for odd numbers up until 30000:
if number in xrange(1, 30000, 2):
pass
eg:
>>> for number in (1, 2, 3, 999999):
print number in xrange(1, 30000, 2)
True
False
True
False
An odd number doesn't divide by 2, so you verify this using the modulo operator:
x % 2
In Python a number not equal to 0 is considered True, so this will do the work:
def work():
x = input("Give me a number : ")
if x in range(30000) and x % 2:
print "hello"
If you wanted to list the numbers, here is a general way to do this (but you should just use the range() function):
def every(increment, range, offset=0):
current = offset
yield current
while(1):
current += increment
if current < range:
yield current
else:
break
So for odds to 30,000 it would be :
for i in every(2, 30000, 1):
...
I am attempting to do Project Euler problem #2. Which is:
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
However the terminal window hangs when I use the following code with 4000000. Smaller numbers run ok. Is there something about this code that is really inefficient, hence the lagginess?
n = int(raw_input("Enter the start number: "))
def fib_generator():
a, b = 0, 1
yield 0
while True:
a, b = b, a + b
yield a
def even_sum(fib_seq):
seq = []
seq = [next(fib_seq) for number in range(n)]
seq = [number for number in seq if number % 2 == 0]
return sum(seq)
def start():
fib = fib_generator()
even_sum = even_sum(fib)
print even_sum
start()
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose values are not more than 4,000,000.
Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ~ n / 5) and that will take an immense amount of time.
Fix the bug, and you'll be okay.
You just need to add logic to stop when the next fibonacci number exceeds 4000000.
Also, I spy a potential problem with this line:
def start():
fib = fib_generator()
even_sum = even_sum(fib) #<--- right here
print even_sum
It isn't good to have a variable name the same as the function name.
Yes, there is something inefficient in your code, you load a very long list into memory twice, with your two seq = ... statements. Why not try one generator expression rather than two list comprehensions? Also, you could alter your Fibonacci generator to stop at a certain number:
def fib_generator(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
def even_sum(fib_seq):
seq = (number for number in fib_seq if not number % 2)
return sum(seq)
def start():
n = int(raw_input('Enter max constraint: '))
fib_seq = fib_generator(n)
even_sum1 = even_sum(fib_seq)
print even_sum1
start()
This ran pretty fast for me
lst = []
num1 = 1
num2 = 2
sum = 0
jump = 0
next = 0
while next<4000000:
next = num1 + num2
if next<4000000:
if jump ==0:
num1 = next
jump = 1
else:
num2 = next
jump = 0
if next%2 == 0:
lst.append(next)
for item in lst:
sum+=item
print ''
print "Sum: ",
print sum