I am learning python and can't get my head around this program.
I just can't seem to find the right loop to get the result.
Q:Create a Python function named sum Of Multiples that has two integer parameters x and n.
Example:sum Of Multiples(3,5);
Expected output:46
This is simple math, the sum is equivalent to 1 + x*(1+2+3+...+n), so 1 + x*(n*(n+1)//2):
def sumOfMultiples(x,n):
print(1+x*n*(n+1)//2)
sumOfMultiples(3, 5)
46
sum = 1 + x + 2x + 3x + ... +
could be written as sum = 1+x(0+1+2+3+...)
so just use a for loop from 0 to n or n+1 depending on where you're supposed to stop and multiply the result with x. Or even shorter use sum and range:
def sumOfMultiples(x, n):
print(1+sum(range(n+1))*x)
The question basically is asking you to sum all n mutliples of x. So just do this,
def sumOfMultiples(x, n):
m_sum = 1
for i in range(1, n+1):
m_sum += i*x
return m_sum
sumOfMultiples(3,5)
You can also do this,
sumOfMultiples = lambda x,n: sum([1] + [x*i for i in range(1, n+1)])
sumOfMultiples(3,5)
Let's just say this should get the job done, but not really optimized:
def sumOfMultiples(x,n):
x_muti = [1]
for i in range(1,n+1):
x_muti.append(x*i)
print(sum(x_muti))
sumOfMultiples(3,5)
Related
I'm studing recursive function and i faced question of
"Print sum of 1 to n with no 'for' or 'while' "
ex ) n = 10
answer =
55
n = 100
answer = 5050
so i coded
import sys
sys.setrecursionlimit(1000000)
sum = 0
def count(n):
global sum
sum += n
if n!=0:
count(n-1)
count(n = int(input()))
print(sum)
I know it's not good way to get right answer, but there was a solution
n=int(input())
def f(x) :
if x==1 :
return 1
else :
return ((x+1)//2)*((x+1)//2)+f(x//2)*2
print(f(n))
and it works super well , but i really don't know how can human think that logic and i have no idea how it works.
Can you guys explain how does it works?
Even if i'm looking that formula but i don't know why he(or she) used like that
And i wonder there is another solution too (I think it's reall important to me)
I'm really noob of python and code so i need you guys help, thank you for watching this
Here is a recursive solution.
def rsum(n):
if n == 1: # BASE CASE
return 1
else: # RECURSIVE CASE
return n + rsum(n-1)
You can also use range and sum to do so.
n = 100
sum_1_to_n = sum(range(n+1))
you can try this:
def f(n):
if n == 1:
return 1
return n + f(n - 1)
print(f(10))
this function basically goes from n to 1 and each time it adds the current n, in the end, it returns the sum of n + n - 1 + ... + 1
In order to get at a recursive solution, you have to (re)define your problems in terms of finding the answer based on the result of a smaller version of the same problem.
In this case you can think of the result sumUpTo(n) as adding n to the result of sumUpTo(n-1). In other words: sumUpTo(n) = n + sumUpTo(n-1).
This only leaves the problem of finding a value of n for which you know the answer without relying on your sumUpTo function. For example sumUpTo(0) = 0. That is called your base condition.
Translating this to Python code, you get:
def sumUpTo(n): return 0 if n==0 else n + sumUpTo(n-1)
Recursive solutions are often very elegant but require a different way of approaching problems. All recursive solutions can be converted to non-recursive (aka iterative) and are generally slower than their iterative counterpart.
The second solution is based on the formula ∑1..n = n*(n+1)/2. To understand this formula, take a number (let's say 7) and pair up the sequence up to that number in increasing order with the same sequence in decreasing order, then add up each pair:
1 2 3 4 5 6 7 = 28
7 6 5 4 3 2 1 = 28
-- -- -- -- -- -- -- --
8 8 8 8 8 8 8 = 56
Every pair will add up to n+1 (8 in this case) and you have n (7) of those pairs. If you add them all up you get n*(n+1) = 56 which correspond to adding the sequence twice. So the sum of the sequence is half of that total n*(n+1)/2 = 28.
The recursion in the second solution reduces the number of iterations but is a bit artificial as it serves only to compensate for the error introduced by propagating the integer division by 2 to each term instead of doing it on the result of n*(n+1). Obviously n//2 * (n+1)//2 isn't the same as n*(n+1)//2 since one of the terms will lose its remainder before the multiplication takes place. But given that the formula to obtain the result mathematically is part of the solution doing more than 1 iteration is pointless.
There are 2 ways to find the answer
1. Recursion
def sum(n):
if n == 1:
return 1
if n <= 0:
return 0
else:
return n + sum(n-1)
print(sum(100))
This is a simple recursion code snippet when you try to apply the recurrent function
F_n = n + F_(n-1) to find the answer
2. Formula
Let S = 1 + 2 + 3 + ... + n
Then let's do something like this
S = 1 + 2 + 3 + ... + n
S = n + (n - 1) + (n - 2) + ... + 1
Let's combine them and we get
2S = (n + 1) + (n + 1) + ... + (n + 1) - n times
From that you get
S = ((n + 1) * n) / 2
So for n = 100, you get
S = 101 * 100 / 2 = 5050
So in python, you will get something like
sum = lambda n: ( (n + 1) * n) / 2
print(sum(100))
def sum_it(n,y):
if n ==0:
return y
else:
return sum_it(n-1,n+y)
required output for sum_it(3,4)i.e. (3+2+1)+4 must be 10
but obtained output is 5
Please how the return really works ?
Altough unclear, it seems like what you need when calling sum_it(n,y) is the sum of natural numbers from 1 to n plus y.
This initial sum is also known as "nth" triangular number.
If that's the case, you actually don't need recursion:
def sum_it(n,y):
return (n*(n+1))//2 + y
If recursion is a must:
def sum_it(n,y):
if (n > 1):
return n + sum_it(n-1,y)
return n + y
Feel free to ask if any doubt remains.
If you intended to sum like (3+2+1) + 4, this code will works.
def sum_it(n,y):
if( n == 1):
return y + 1
else:
return(n + sum_it(n-1,y))
For example, sum_it(3,4) works like below
sum_it(3,4) returns 3 + sum_it(2,4)
sum_it(2,4) returns 2 + sum_it(1,4)
sum_it(1,4) returns 1 + 4
It means
sum_it(3,4) returns 3 + 2 + 1 + 4
I'm being asked to add the first 100 terms f the sequence (1 + 1/2 + 1/4 + 1/8 ...etc)
what i ve been trying is something Iike
for x in range(101):
n = ((1)/(2**x))
sum(n)
gives me an error, guess you cant put ranges to a power
print(n)
will give me a list of all the values, but i need them summed together
anyone able to give me a hand?
using qtconsole if that's of any relevance, i'm quite new to this if you haven't already guessed
You keep only one value at a time. If you want the sum, you need to aggregate the results, and for that you'd need an initial value, to which you can add each round the current term:
n = 0 # initial value
for x in range(100):
n += 1 / 2**x # add current term
print(n)
Hmm, there is actually a formula for sum of geometric series:
In your question, a is 1, r is 0.5 and n is 100
So we can do like
a = 1
r = 0.5
n = 100
print(a * (1 - r ** n) / (1 - r))
It is important to initialize sum_n to zero. With each iteration, you add (1/2**x) from your sequence/series to sum_n until you reach n_range.
n_range = 101
sum_n = 0 # initialize sum_n to zero
for x in range(n_range):
sum_n += (1/(2**x))
print(sum_n)
You are getting an error because sum takes an iterable and you are passing it a float:
sum(iterable[, start])
To solve your problem, as others have suggested, you need to init an accumulator and add your power on every iteration.
If you absolutely must use the sum function:
>>> import math
>>> sum(map(lambda x:math.pow(2,-x),range(100)))
2.0
I was trying to calculate value of pi using this formula:
I had written this code for finding it for a given n:
def pisum(n):
sum=3.0
x=2.0
while (n>0):
if n%2==1:
sum=sum+(4/(x*(x+1)*(x+2)))
else :
sum=sum-(4/(x*(x+1)*(x+2)))
x=x+2
n=n-1
return str(sum)
It runs fine for n=0 and n=1 and gives output 3.0, 3.16666666667. But for n=50 the output should be 3.1415907698497954 but it is giving 2.85840923015. Why so much difference? Please help to correct if i had done something wrong.
The problem is that you are using n%2 in order to determine whether to subtract or add. It is not the amount of loops that you start with that should matter, but which loop you're in. To see that, try using your function for an odd number, e.g. 51 and you will see that it will give you a correct answer.
To explain further, if you start with n=50, you will initially subtract (4/(x*(x+1)*(x+2))) from 3 rather than add to it, but if you start with n=51, you will initially add.
If you modify your function as follows:
def pisum(n):
sum = 3.0
x = 2.0
for i in range(n):
if i % 2 == 0:
sum = sum + (4 / (x * (x + 1) * (x + 2)))
else:
sum = sum - (4 / (x * (x + 1) * (x + 2)))
x = x + 2
return str(sum)
you will always get a correct result.
You made a small mistake.
One correct program:
def pisum(n):
sum = 3.
for i in xrange(2, 2*n+2, 2):
sum += (4. if (i&2) == 2 else -4.)/i/(i+1)/(i+2)
return sum
Being more conservative with number of lines:
def pisum(n):
return 3. + sum([(4. if (i&2) == 2 else -4.)/i/(i+1)/(i+2) for i in xrange(2,2*n+2,2)])
Mistake in yours:
You are iterating on n in reverse, thus one time (odd value of n) you are calculating:
and for another value of n (even value apart from 0) you are calculating
I am trying to make a code (in python) where I can input a range and it will find the sum off all the numbers besides the ones that are divisible by x (which i also choose).
For example:
if the range is 0<N<10 and x = 3 then I want the code to sum the numbers
1 + 2 + 4 + 5 + 7 + 8
and output 27.
or if the range is 0<N<5 and x = 2 I want the code to sum the numbers
1 + 3
and output 4
But, the problem is I have no idea how to do it. Can anyone help me?
For your second example: (0<N<5, x=2):
sum(i for i in range(1, 5) if i%2)
def fn(N, x):
total = 0
for i in range(N):
if i%x:
total += i
return total
Read up on loops and ranges in python if you are new.
You could do something like this:
>>> div = 3
>>> n = 10
>>> num_div = filter(lambda x: x%div, range(n))
>>> sum(num_div)
27
or as a function
def func(n,div):
return sum(filter(lambda x: x%div, range(n))
The other answers implicitly assume the range will always start from 0. If you want to be able to set both the start and end points of your range, you could use:
def sumrange(start, stop, n):
return sum(i for i in range(start, stop) if i%n)