reading-notes

Class 04

Classes and Objects

Source: Classes and Objects

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

Thinking Recursively

Source: Thinking Recursively

Structure

Example

n!

def factorial_recursive(n):
    # Base case: 1! = 1
    if n == 1:
        return 1

    # Recursive case: n! = n * (n-1)!
    else:
        return n * factorial_recursive(n-1)

Stack

stack gif

State

Options

  1. Thread state through each call

     def sum_recursive(current_number, accumulated_sum):
     # Base case
     # Return the final state
     if current_number == 11:
         return accumulated_sum
    
     # Recursive case
     # Thread the state through the recursive call
     else:
         return sum_recursive(current_number + 1, accumulated_sum + current_number)
    
  2. Maintain state inn global scope

    # Global mutable state
     current_number = 1
     accumulated_sum = 0
    
    
     def sum_recursive():
         global current_number
         global accumulated_sum
         # Base case
         if current_number == 11:
             return accumulated_sum
         # Recursive case
         else:
             accumulated_sum = accumulated_sum + current_number
             current_number = current_number + 1
             return sum_recursive()
    

Data structures

List Sum Example:

    # Base case
    if input_list == []:
        return 0

    # Recursive case
    # Decompose the original problem into simpler instances of the same problem
    # by making use of the fact that the input is a recursive data structure
    # and can be deļ¬ned in terms of a smaller version of itself
    else:
        head = input_list[0]
        smaller_list = input_list[1:]
        return head + list_sum_recursive(smaller_list)
>>> list_sum_recursive([1, 2, 3])
6

Pytest

Source: Python Testing with pytest: Fixtures and Coverage

Fictures

Function

def reverse_lines(f):
   return [one_line.rstrip()[::-1] + '\n'
           for one_line in f]

Fixture

@pytest.fixture
def simple_file():
   return StringIO('\n'.join(['abc', 'def', 'ghi', 'jkl']))
@pytest.fixture(scope='module')
def simple_file():
   return StringIO('\n'.join(['abc', 'def', 'ghi', 'jkl']))

Coverage

Indicates a reasonable degree of test coverage (cases to test)