Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
The use of for loops is not allowed. This program is designed to calculate values up to number 'n' which is a value entered by the user. Help on this would be appreciated. A photo of the problem and my code so far is listed below:
import math
counterN = 0 #Numerator
counterD = 0 #Denominator
divNumber = 0 #Numerator/Denominator
nValue = 0 #Variable to add numberator values to
dValue = 0 #Variable to add denominaor values to
#Prompts user for a
print("Please enter a value for calculation: ")
number = int(input())
if (number <= 0):
print("Invalid input given.")
#Adds the numerator up to number entered by user
while (counterN <= number):
counterN = counterN + 1
nValue += counterN
#Denominator calculation
counterD = counterD + 1
dValue += counterD
divNumber = nValue / dValue
divNumber += divNumber
#Outputs value to user
print("The result is" , divNumber)
print(counterN, nValue)
You can use recursion for such problems. I've written a recursive solution for you which I found very intuitive-
global SUM
SUM = 0
def fracSUMCalc(n):
if n == 1:
return 1
SUM = fracSUMCalc(n-1) + (sum(range(1, n+1)) / n)
return SUM
print(fracSUMCalc(n=998))
This prints out 249749.5 which is the answer to the sum of your series till n=998. You can vary n as per your need.
Please note that this solution will work fine on any standard modern day laptop till n=998. For n>998, you'd either have to increase your machine's recursion depth limit or use a different approach to develop a more efficient program.
There is a solution that just uses no loops or recursion at all, just maths
def frac_series_sum(n):
return n + sum(range(n)) * 0.5
print(frac_series_sum(1)) # 1.0
print(frac_series_sum(5)) # 10.0
print(frac_series_sum(100)) # 2575.0
It can be shown (see below) that your sum is equal to
for any natural number n.
Thus, this function calculates the sum you want. It does not involve any recursion, for loops or any kind of iteration (it is O(1)):
def my_calc(n):
"Returns 1/1 + (1 + 2)/2 + ... + (1 + 2 + ... + n)/n"
return 0.25 * n * (n + 3)
This is as efficient as it gets.
If you are not allowed to use the solution above and you need to use a while loop:
def my_inefficient_calc(n):
"Returns 1/1 + (1 + 2)/2 + ... + (1 + 2 + ... + n)/n"
result = 0
i = 1
while (i <= n):
result += (sum(range(1, i + 1))) / i
i += 1
return result
If you are not allowed to use the built-in sum function, you can calculate the sum using a nested while loop:
def even_less_efficient(n):
"Returns 1/1 + (1 + 2)/2 + ... + (1 + 2 + ... + n)/n"
result = 0
i = 1
while (i <= n):
inner_sum = 0
k = 1
while (k <= i):
inner_sum += k
k += 1
result += inner_sum / i
i += 1
return result
i is a loop variable (counter) for the outer loop. It ranges from i = 1 up to n.
k is a loop variable (counter) for the inner loop. It ranges from k = 1 up to i.
The inner loop is responsible for calculating the sum in the numerator for each term. This sum is stored in inner_sum.
Once the sum is calculated for a given i (i.e. once we are done with the inner loop), we divide this sum by i to get one of the terms in the mathematical expression.
The outer loop is responsible for summing all of the terms from i = 1 up to n.
Intuitive Proof
How did I arrive at this?
You want a program that calculates the following sum:
This is an elegant solution that has stuck with me for a long time that I will never forget. I once learned in real analysis of a famous mathematician who at the age of 5 (if I remember correctly) reasoned that the sum of i from i = 1 up to k is:
He did so by writing out the sum twice, but the second in reverse order:
(sum of i from i = 1 to k) = 1 + 2 + ... + (k - 1) + k
(sum of i from i = 1 to k) = k + (k - 1) + ... + 2 + 1
----------------------------------------------------------
(k+1)+ (k+1) +... + (k+1) + (k+1) # k terms
He noticed that each sum has k numbers and the sum of each column is equal to k + 1. So, if you add the two sums, you get
2 * (sum of i from i = 1 to k) = k * (k + 1)
Thus
(sum of i from i = 1 to k) = (k * (k + 1)) / 2
which is the same as the result in the second image above.
Substitution of this result into the left-hand-side of the expression in the first image:
Now apply the result that we derived again to the last expression above:
Thus
or
0.25 * n * (n + 3)
Note: A formal proof of the above result would be a proof by induction to show it is true for any natural number n. This proof by induction part is the easy part. I have omitted such a proof as the above should be obvious to anyone that sees it.
Bro, I just did easier
counterN = 1 #Numerator
result = []
#Prompts user for a
print("Please enter a value for calculation: ")
number = int(input())
if (number <= 0):
print("Invalid input given.")
#Adds the numerator up to number entered by user
while (counterN <= number):
numerator = sum(range(counterN+1))
denominator = counterN
result.append(numerator / denominator)
#solucion
counterN += 1
#Outputs value to user
print("The result is" , sum(result))
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
Problem Statement
Edit: I have transcribed the image as suggested although I think some terms are better shown in the picture if anything is unclear here;
This function takes in a positive integer n and returns the sum of the following series Sn, as long as the absolute value of each term is larger than stop.
Sn= 1 − 1/2 + 1/3 − 1/4 + ... + (−1)n+1/n + ...
You can assume that stop is a float value and 0 < stop < 1.
You need not round the output.
For example, if stop = 0.249, then Sn is evaluated with only four terms.
Sn = 1 − 1/2 + 1/3 − 1/4
For example, if stop = 0.199, then Sn is evaluated with only five terms.
Sn = 1 − 1/2 + 1/3 − 1/4 + 1/5
The built-in function abs() is useful. You should use a while loop.
Test cases:
print( alternating_while(0.249) )
print( alternating_while(0.199) )
gives:
0.5833333333333333
0.7833333333333332
Now for this question, I want to get the sum of this series based on the conditions stipulated in the question.
My problem is I don't understand how to type the formula given in the question because I'm not familiar with how the while-loop works. Can someone instruct me on how to?
def alternating_while(stop):
total = 0
n = 1
term = 1
while abs(term) > stop:
total= (-1) ** (n + 1) / n + alternating_while(n - 1)
return total
No reason to use recursion as it wasn't mentioned as a requirement. Just check the term in the while loop for the stop condition:
Python 3.8+ (for the := operator):
def alternating_while(stop):
n = 1
total = 0
while abs(term := (-1)**(n+1)/n) > stop:
total += term
n += 1
return total
print(alternating_while(0.249))
print(alternating_while(0.199))
Output:
0.5833333333333333
0.7833333333333332
Pre-Python 3.8 version:
def alternating_while(stop):
n = 1
total = 0
while True:
term = (-1)**(n+1)/n
if abs(term) <= stop:
break
total += term
n += 1
return total
Or:
def alternating_while(stop):
n = 1
total = 0
term = (-1)**(n+1)/n
while abs(term) > stop:
total += term
n += 1
term = (-1)**(n+1)/n # redundant
return total
The key is "alternating". You can just increment the current denominator one at a time. If it is odd, you add. Otherwise, you subtract. abs is not really required; I'm not sure why they would mention it.
def alternating_while(stop):
total = 0
denom = 1
while 1/denom > stop:
if denom & 1:
total += 1/denom
else:
total -= 1/denom
denom += 1
return total
print(alternating_while(0.249))
print(alternating_while(0.199))
Output:
0.5833333333333333
0.7833333333333332
You need to cycle between adding and subtracting. The itertools module has a very helpful cycle class which you could utilise thus:
from itertools import cycle
from operator import add, sub
def get_term(d=2):
while True:
yield 1 / d
d += 1
def calc(stop=0.199):
c = cycle((sub, add))
term = get_term()
Sn = 1
while (t := next(term)) > stop:
Sn = next(c)(Sn, t)
return Sn
print(calc())
Output:
0.6936474305598223
Note:
The reference in the problem statement to absolute values seems to be irrelevant as no terms will ever be negative
I understand you need to use while in this particular problem, and this answer won't immediately help you as it is probably a few steps ahead of the current level of your course. The hope however is that you'll find it intriguing, and will perhaps come back to it in the future when you start being interested in performance and the topics introduced here.
from math import ceil
def f(stop):
n = ceil(1 / stop) - 1
return sum([(2 * (k & 1) - 1) / k for k in range(1, n + 1)])
Explanation
First, we want to establish ahead of time n, so that we avoid a math evaluation at each loop to decide whether to stop or not. Instead, the main loop is now for k in range(1, n + 1) which will go from 1 to n, included.
We use the oddness of k (k & 1) to determine the sign of each term, i.e. +1 for k == 1, -1 for k == 2, etc.
We make the series of terms in a list comprehension (for speed).
(A point often missed by many Pythonistas): building the list using such a comprehension and then summing it is, counter-intuitively, slightly faster than summing directly from a generator. In other words, sum([expr for k in generator]) is faster than sum(expr for k in generator). Note: I haven't tested this with Python 3.11 and that version of Python has many speed improvements.
For fun, you can change slightly the loop above to return the elements of the terms and inspect them:
def g(stop):
n = ceil(1 / stop) - 1
return [(2 * (k & 0x1) - 1, k) for k in range(1, n + 1)]
>>> g(.249)
[(1, 1), (-1, 2), (1, 3), (-1, 4)]
I am doing an assessment that is asking by the given "n" as input which is a length of a stick; how many triangles can you make? (3 < n < 1,000,000)
For example:
input: N=8
output: 1
explanation:
(3,3,2)
input: N=12
output: 3
explanation:
(4,4,4) (4,5,3) (5,5,2)
Now the codes I wrote are returning 33 % accuracy as the web assessment is throwing time limit error.
ans = 0
n = int(input())
for a in range(1, n + 1):
for b in range(a, n - a + 1):
c = n - a - b
if a + b > c >= b:
ans += 1
print(ans)
code b:
ans = 0
n = int(input())
for i in range(1,n):
for j in range(i,n):
for c in range(j,n):
if(i+j+c==n and i+j>c):
ans+=1
print(ans)
How can this be made faster?
This is an intuitive O(n) algorithm I came up with:
def main():
n = int(input())
if n < 3:
print(0)
return
ans = n % 2
for a in range(2, n//2+1):
diff = n - a
if diff // 2 < a:
break
if diff % 2 == 0:
b = diff // 2
else:
b = diff // 2 + 1
b = max(b - a // 2, a)
c = n - b - a
if abs(b - c) >= a:
b += 1
c -= 1
ans += abs(b-c)//2 + 1
print(ans)
main()
I find the upper bound and lower bound for b and c and count the values in that range.
I thought of a completely different way to do it:
We take the smallest side and call it a. It can never be more than n/3, otherwise a different side would be the smallest.
We try to figure out what is the next smallest side (b):
We see what's left after reducing our a.
We divide it by 2 in order to find the middle where we'll start advancing from
We'll see how far we can get before the difference between the lengths is a (or the difference from the middle is a/2) as that's the minimum b side length that is possible and satisfies a+b>c. Basically, the second smallest side is a/2 less than the middle.
The smallest side is the maximum between our calculation or a, in caseb==a. b can never be lower than a as it violates our first rule that a is the smallest.
We figure out the difference from the middle and the smallest side. That's how many possible solutions we have for the other 2 sides.
Add everything together for every a and that's our solution.
The floor, ceil and % are fixes for when a is odd, the middle is .5, or +1 in case b+c is even, cause b==c is then possible.
Code:
import math
n = int(input("Enter a number: "))
total = 0
# a is the shortest side
for a in range(1, (n//3)+1):
length_left = n-a
middle_number = length_left/2
# Shortest potential side b where the distance between b and c is smaller than a (c-b < a)
b = middle_number-(math.ceil(a/2)-1)-((length_left % 2)/2)
# We calculate how far it is from the middle
max_distance_from_middle = middle_number - max(b, a)
# Add another 1 if the length is even, in case b==c
adding = math.floor(max_distance_from_middle) + (1 if length_left % 2 == 0 else 0)
total += adding
print(total)
Or in an ugly one-liner:
n = int(input("Enter a number: "))
print(sum(math.floor((n-a)/2 - max((n-a)/2 - math.ceil(a/2) + 1 - (((n-a) % 2)/2), a)) + 1 - ((n-a) % 2) for a in range(1, (n//3)+1)))
Alcuin's sequence expansion: O(1)
Alcuin's sequence [See: https://en.wikipedia.org/wiki/Alcuin%27s_sequence] is a series expansion of the polynomial below, where the nth coefficient corresponds to the nth answer, that is, the maximum amount of unique integer triangles with perimeter n.
The algorithmic implementation of this is simply a formula. The Online Encyclopaedia of Integer Sequences (OEIS) provides many formulas that achieve this, the simplest of which is:
round(n^2 / 48) (Even)
round((n+3)^2 / 48) (Odd)
[See: https://oeis.org/A005044]
This evidently has a constant time complexity, given that the only functions required are modulo 2, integer squared and round, each of which are constant time (under certain definitions).
Implementation
Expanded:
def triangles(n):
if n % 2 == 0:
return round(n ** 2 / 48)
else:
return round((n + 3) ** 2 / 48)
1-Liner:
def triangles(n): return round(n ** 2 / 48) if n%2==0 else round((n + 3) ** 2 / 48)
Or even:
def triangles(n): return round((n + 3 * n%2) ** 2 / 48)
Extra
No imports are needed.
As the OP questioned, why do we divide by 48? While I can't answer that explicitly, let's get an intuitive understanding. We are squaring numbers, so it is evidently going to expand greatly. By the time we get to 5, that would give 64 (8^2). So, there must be a constant (albeit a reciprocal) to restrict the growth of the parabola, thus the / 48.
When we graph the OP's method, it gives an alternating parabola. This explains why there is a back-and-forth with the +3 and +0.
https://mathworld.wolfram.com/AlcuinsSequence.html
import math
n = int(input())
print(round(n ** 2 / 48)) if n % 2 == 0 else print(round((n + 3)** 2 / 48))
FIND THE SEQUENCE SUM
i = 5
j = 9
K = 6
sum all the values from i to j and back to K: 5 + 6 + 7 + 8 + 9 + 8 + 7 + 6
My answer is:
def sequence_sum(i,j,k):
sum = 0
for i in range(i,j+1):
sum += i
for m in range(j-1,k-1,-1):
sum += m
return sum
However, this solution is correct I received a 9/12 out of the test cases and was given an error message that stated that the time limit was exceeded, I was allowed 10 seconds and the message read " Your code did not execute within the time limits. Please optimise your code."
Can I please get some help with this as I don't understand what I am suppose to do here?
Notice the sum from 5 to 9 is the same as:
(5+0) + (5+1) + (5+2) + (5+3) + (5+4)
If we extract 5, we have: 5*(9-5+1) + (sum from 1 to (9-5)).
To get a general formula:
sum(a,b) = (b-a+1) * a + (b-a)*(b-a+1)/2
The second formula is the sum of all natural numbers up to b-a.
so create the following function:
def my_sum(a,b):
return (b-a+1) * a + (b-a)*(b-a+1)/2
thus the sequence_sum(i,j,k):
def sequence_sum(i,j,k):
return my_sum(i,j) + my_sum(k,j-1)
You can simply use range() function returning an iterable + sum function:
sum's time complexity is O(n) and the range function returns a lazy iterable. That is also O(n) operation.
The return statement returns only the reference of the list so it's time complexity is O(1)
return sum(range(i,j))+sum(range(j,k-1,-1))
the sum from 1, to i is i * (i + 1) / 2 let's call it s(i).
and f(i, j) is the sum from i to j.
f(i, j) = i + (i + 1) + ... + j = 1 + 2 + ... + j - (1 + 2 + ... + (i - 1))
so f(i, j) = s(j) - s(i-1)
the sum from j back to k (but we have to eliminate j because already counted), is the same as the sum from k to j-1 which is f(k, j-1) = s(j-1) - s(k-1)
The total answer is: s(j) - s(i-1) + s(j-1) - s(k-1).
The complexity of sfunction is O(1) so this should pass the test cases
Simpler formula for a range sum, including its derivation:
5 + 6 + 7 + 8
= (write all numbers twice and halve the sum)
(5 + 6 + 7 + 8 +
8 + 7 + 6 + 5) / 2
= (sum each vertical pair)
(13 + 13 + 13 + 13) / 2
=
4 * 13 / 2
=
(8 - 5 + 1) * (5 + 8) / 2
So in general for the sum from i to j: (j - i + 1) * (i + j) / 2
TLE is the case here. So you need to optimize your code.
For that, we can have two approaches.
1st approach: Simple looping
Apply a loop from i to j. And check if the current number is greater than or equal to k. If it is then add 2 times of current number. Else keep adding it once.
for n in range(i,j+1):
if n>=k:
sum+= 2*n
else:
sum+= n
2nd approach: Maths
We know that sum of first n integers is n*(n+1)/2
So what you can do is find sum till j, remove the sum till i (i excluded) from it.
Similarly, for k, find the sum till j and remove the sum till k (k excluded) from it.
Add remaining sums of both minus j as it will get considered twice.
i.e.
sum1 = j*(j+1)/2 - i*i(i-1)/2
sum2 = j*(j+1)/2 - k*(k-1)/2
ans = sum1+sum2 - j;
I'm trying a challenge. The idea is the following:
"Your task is to construct a building which will be a pile of n cubes.
The cube at the bottom will have a volume of n^3, the cube above will
have volume of (n-1)^3 and so on until the top which will have a
volume of 1^3.
You are given the total volume m of the building. Being given m can
you find the number n of cubes you will have to build? If no such n
exists return -1"
I saw that apparently:
2³ + 1 = 9 = 3² and 3 - 1 = 2
3³ + 2³ + 1 = 36 = 6² and 6 - 3 = 3
4³ + 3³ + 2³ + 1 = 100 = 10² and 10 - 6 = 4
5³ + 4³ + 3³ + 2³ + 1 = 225 = 15² and 15 - 10 = 5
6³ + 5³ + 4³ + 3³ + 2³ + 1 = 441 = 21² and 21 - 15 = 6
So if I thought, if I check that a certain number is a square root I can already exclude a few. Then I can start a variable at 1 at take that value (incrementing it) from the square root. The values will eventually match or the former square root will become negative.
So I wrote this code:
def find_nb(m):
x = m**0.5
if (x%1==0):
c = 1
while (x != c and x > 0):
x = x - c
c = c + 1
if (x == c):
return c
else:
return -1
return -1
Shouldn't this work? What am I missing?
I fail a third of the sample set, per example: 10170290665425347857 should be -1 and in my program it gives 79863.
Am I missing something obvious?
You're running up against a floating point precision problem. Namely, we have
In [101]: (10170290665425347857)**0.5
Out[101]: 3189089316.0
In [102]: ((10170290665425347857)**0.5) % 1
Out[102]: 0.0
and so the inner branch is taken, even though it's not actually a square:
In [103]: int((10170290665425347857)**0.5)**2
Out[103]: 10170290665425347856
If you borrow one of the many integer square root options from this question and verify that the sqrt squared gives the original number, you should be okay with your algorithm, at least if I haven't overlooked some corner case.
(Aside: you've already noticed the critical pattern. The numbers 1, 3, 6, 10, 15.. are quite famous and have a formula of their own, which you could use to solve for whether there is such a number that works directly.)
DSM's answer is the one, but to add my two cents to improve the solution...
This expression from Brilliant.org is for summing cube numbers:
sum of k**3 from k=1 to n:
n**2 * (n+1)**2 / 4
This can of course be solved for the total volume in question. This here is one of the four solutions (requiring both n and v to be positive):
from math import sqrt
def n(v):
return 1/2*(sqrt(8*sqrt(v) + 1) - 1)
But this function also returns 79863.0. Now, if we sum all the cube numbers from 1 to n, we get a slightly different result due to the precision error:
v = 10170290665425347857
cubes = n(v) # 79863
x = sum([i**3 for i in range(cubes+1)])
# x = 10170290665425347857, original
x -> 10170290665425347856
I don't know if your answer is correct, but I have another solution to this problem which is waaaay easier
def max_level(remain_volume, currLevel):
if remain_volume < currLevel ** 3:
return -1
if remain_volume == currLevel ** 3:
return currLevel
return max_level(remain_volume - currLevel**3, currLevel + 1)
And you find out the answer with max_level(m, 0). It takes O(n) time and O(1) memory.
I have found a simple solution over this in PHP as per my requirement.
function findNb($m) {
$total = 0;
$n = 0;
while($total < $m) {
$n += 1;
$total += $n ** 3;
}
return $total === $m ? $n : -1;
}
In Python it would be:
def find_nb(m):
total = 0
n = 0
while (total < m):
n = n + 1
total = total + n ** 3
return n if total == m else -1
def count(n):
if n == 0 or n == 1:
return 1
else:
sum = 0
left = 0
right = 0
for x in range(1,n+1):
left = count(x-1)
right = count(n-x)
sum += left * right
return sum
I was reading this post and I wondered
if no of different binary search trees from n nodes is
(2n)! / ((n+1)! * n!)
from this post.
Then
what will be the time complexity ? O(n!) ?
what will be the recurrence relation ?
When you call count(n), it's calling each of count(0) to count(n-1) twice.
So I think you can write the recurrence like this:
T(n) = 2 * sum[T(0) upto T(n-1)] + nk where k represents the multiplication and summation part.
Now consider:
T(n+1) = 2 * sum[T(0) upto T(n)] + (n+1)k
= 2 * sum[T(0) upto T(n-1)] + 2T(n) + nk + k
= T(n) + 2T(n) + k
= 3T(n) + O(1)
Solving this, it appears to be of O(3^n) complexity.