Maintaining the Single Responsibility Principle with Project Euler #2 This is my solution to Project Euler problem 2:


  By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.


The class fibonacci_Even_Sum_Calculator does two things:


calculate the sum of the even-valued Fibonacci numbers
cache the results in a dictionary


Is this a sign that this code violates the Single Responsibility Principle?

class fibonacci_Even_Sum_Calculator:

        def __init__(self):
                self.cached_result = dict()

        def F(self, n):

                if n == 0: 
                        return 0
                elif n == 1: 
                        return 1
                else:
                        if(self.cached_result.has_key(n)):
                                return self.cached_result[n]
                        else:
                                result = self.F(n-1) + self.F(n-2)
                                self.cached_result[n] = result 
                                return result

        def is_even(self, number):
                return number % 2 == 0

        def get_result(self,limit_value):

                sequence = 2
                sum = 0

                while True:

                        result = self.F(sequence)

                        if result &gt; limit_value:
                                break

                        if self.is_even(result) :
                                sum = sum + result

                        sequence = sequence + 1

                return sum

fibonacci_calculator = fibonacci_Even_Sum_Calculator() 
result = fibonacci_calculator.get_result(4000000)
print result
I think you are violating SRP, but not for the reason you think you are. Memoization is fine, it's definitely one approach to calculating the fibonacci values, but you have one class that is doing BOTH calculating the Fibonacci values AND summing the even ones. 

If you are really worried about SRP, I would have a generator to calculate the Fibonacci numbers, and then an external function to sum them:

def sum_evens(limit):
    sum = 0
    for f in fibonacci_numbers(): # left as an exercise
        if f &gt; limit: 
            break
        elif f % 2 == 0:
            sum += f
    return sum


Otherwise, minor notes, your class is named fibonacci_Even_Sum_Calculator. The most accepted convention for class names is CamelCase, so FibonacciEvenSumCalculator is strongly preferred. Similarly, function names should be lowercase, and f is an insufficient name for code that is "get the nth Fibonacci number".