Reputation: 189
How would I solve this?
The program should contain the definition for the function sumTri(cutOff)
. The function adds Tri numbers into the sum.
Tri numbers are every third number: 1, 4, 7, 10,
.... The function adds consecutive Tri numbers 1, 4, 7,
... into the sum so long as the Tri number is less than the cutOff. The function returns the sum of these numbers.
Upvotes: 0
Views: 309
Reputation: 304127
This sequence is related to triangular numbers
Here is one that is O(1)
def sumTri(cutoff):
n = (cutoff+1)//3
return (3*n-1)*n//2
Upvotes: 4
Reputation: 64563
It's simple:
def sumTri(cutOff):
return sum(range(1,cutOff,3))
Or, when you need it lowlevel:
def sumTri(cutOff):
sum = 0
tri = 1
while tri < cutOff:
sum += tri
tri += 3
return sum
I'll try to explain both soultions a little bit.
In the first case you use two "highlevel" functions of Python, that make all work for you: sum
and range
. The range(a,b,c)
function generates a list of numbers from a
to b
with the step c
between. E.g.:
In [1]: range(1,10,3)
Out[1]: [1, 4, 7]
In [2]: range(1,22,3)
Out[2]: [1, 4, 7, 10, 13, 16, 19]
You must note here that range
generates numbers until the number in the list is less than b
, not less-or-equal. Exactly what you need for your task.
And sum
obviously calculates and returns the sum of the numbers in the list that it has as its argument:
In [3]: sum([1])
Out[3]: 1
In [4]: sum([1,2])
Out[4]: 3
In [5]: sum([1,2,3])
Out[5]: 6
Now you need just to combine these two functions:
return sum(range(1,cutOff,3))
The second solution is more "lowlevel" and "algorithmic". You use no special python functions here and do everything yourself.
You use two variable to calculate the sum:
sum
-- the variable where you store your sumtri
-- the variable with the current value of number that you add step by stepWhen you write something like:
a = a + 5
that means: "Now I want a
to be equal to what a
was before plus 5" or "increase a
by 5". You can write it shorter:
a += 5
These two forms are equivalent.
But you need not simple add something. You need to do it for many times until something is happened. In python you do it using while
:
while someting-is-true:
do-something
Every time while
checks the something-is-true
condition, and when it's True, it makes commands that are under while
(indented) i.e. do-something
.
Now you know all necessary to write the solution:
def sumTri(cutOff):
sum = 0 # we start the sum from 0
tri = 1 # and the first number to add is 1
while tri < cutOff: # next number to add < cutOff?
sum += tri # than add it to sum
tri += 3 # and increase the number by 3
return sum # now you have the result, return it
That was the function that makes the job. Now you can use the function. How you do this?
def sumTri(cutOff):
...
# anywhere in you program:
# presuming a is the cutOff
print sumTri(a)
when you want to run the function and use its result you just write function_name(args)
.
Upvotes: 5