In [10]:
def frizz_buzz(number):
"""
Calculates the sum of the all the multiples of 3 or 5 of `n`.
@param n -- a non-negative integer
@return integer
"""
mutliples_of_three_and_five = lambda x: x if (x % 5 == 0) or (x % 3 == 0) else 0
return sum(map(mutliples_of_three_and_five, range(number)))
In [11]:
%timeit frizz_buzz(1000)
In [12]:
import time
start = time.time()
result = frizz_buzz(1000)
elapsed = time.time() - start
print "result %s returned in %s seconds" % (result,elapsed)
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.
In [25]:
def fib(n):
"""
Calculates the `nth` value of the fibbonacci sequence.
@param n -- a non-negative integer
@return integer
"""
# base case
if n < 2:
return n
return fib(n-1) + fib(n-2)
In [26]:
from unittest import TestCase
class test_if_fib_outptus_fibonacci_sequence(TestCase):
def setUp(self):
self.input = range(10)
self.output = [0, 1, 1, 2, 3, 5, 8, 13 , 21, 34, 55]
def test_if_fib_correctly_ouptuts_values_less_than_10(self):
self.AssertEqual(self.output, [fib(i) for i in self.input])
if __name__ == '__main__':
unittest.main()
In [ ]:
assert fib(4) == 3
assert fib(8) == 21
In [91]:
def even_fib(limit):
"""
Calculates the sum of even values in the fibbonacci sequence up to the given limit.
@param limit -- a non-negative integer
@return integer
"""
limit += 2
total = 0
for n in xrange(2, limit):
value = fib(n)
if value % 2 == 0:
total += value
return total
In [86]:
from unittest import TestCase
class TestEvenFib(TestCase):
def setUp(self):
self.input = 4000000
self.even_fib_sum_of_10 = 44
self.even_fib_sum_of_4_millio
def test_even_fib_outputs_correct_sum(self):
self.assertEqual(self.input, even_fib(self.output))
if __name__ = 'main':
unittest.main()
In [92]:
even_fib(10)
Out[92]:
In [94]:
sum([x for x in [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] if x%2 ==0])
Out[94]:
In [ ]: