“Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.”
The Task: Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren’t.
# Problem Parameters
import codewars_test as test
from solution import lovefunc
@test.describe("Fixed Tests")
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
test.assert_equals(lovefunc(1,4), True)
test.assert_equals(lovefunc(2,2), False)
test.assert_equals(lovefunc(0,1), True)
test.assert_equals(lovefunc(0,0), False)
Before we begin writing any code, lets look at this like a software engineer. There are a number of steps we’ll need to take in advance to get an idea of the scope, requirements, rules and restrictions. We’ll need to discover which data types and algorithms would work best for this problem before writing some pseudo code.
Step One: Understanding the Problem
To approach the problem systematically, we start by breaking it down into smaller components. Then, we focus on understanding how these components relate to each other, forming a clear picture of the problem’s structure. At this point, we should also note key components, constraints and expected outcomes.
Lets break down this problem into small pieces:
Step Two: Research Potential Solutions
During this step, we’ll explore different resources like documentation and forums to learn about potential solutions. Studying existing solutions and learning from others experiences, we can broaden our understanding, identifying potential strategies and even gain insights into relevant algorithms and data structures.
In summary:
Step Three: Plan and Design
During the planning phase, we break the problem into smaller parts to better understand its complexity. We explore different strategies and algorithms for solving each part and select the most appropriate approach that aligns with the problem requirements and constraints.
In summary:
Step Four: Implementation
Using Python’s conditional statements, the function evaluates petal parity and returns True if one flower has an even number of petals and the other has an odd number, and False otherwise. This implementation demonstrates the practical application of our problem-solving approach.
Here is the completed code:
#CodeWars Exercise One: Opposites Attract
def lovefunc( flower1, flower2 ):
if flower1 % 2 == 0 and not flower2 % 2 == 0:
return True
if not flower1 % 2 == 0 and flower2 % 2 == 0:
return True
else:
return False
Step Five: Optimisation and Big O
I’m just kidding, sort of. This could be so much more efficient and will be.. soon!