After posting my first question on here (FizzBuzz in Python using a class) I got a lot of great feedback. I've decided to try another code kata and write it as cleanly as possible.
The code kata of oddeven consists of the following tasks:
Given a max number a string should be returned counting up to and including that max number and adhere to the following rules in order:
- Print "Even" instead of number, if the number is even, means divisible by 2
- Print "Odd" instead of number, if the number is odd means not divisible by 2 and is not a Prime [hint - it should be a Composite]
- Print number, if it does not meet above two conditions.
I came up with the following code and would like to know what you think. This way I know if I have the right mindset.
code:
def create_oddeven_string(max_number):
"""Returns a string with numbers up to and including max_number."""
return ",".join(create_oddeven_list(max_number))
def create_oddeven_list(max_number):
"""Returns a list with string representations of oddeven parsed numbers up to and
including the max_number."""
return map(parse_oddeven_number, xrange(1, max_number+1))
def parse_oddeven_number(number):
"""Returns the string "Even" when number is even, "Odd" when number is odd
and composite, or the string representation of the number if prime."""
if is_divisable(number, 2):
return "Even"
elif is_composite(number):
return "Odd"
else:
return str(number)
def is_divisable(number, modulo):
"""Returns True if number % modulo == 0."""
return number % modulo == 0
def is_composite(number):
"""Returns True if number is not a prime number (only divisable by itself and 1)."""
if number <= 3:
return False
elif is_divisable(number, 2) or is_divisable(number, 3):
return True
else:
i = 5
while i*i <= number:
if is_divisable(number, i) or is_divisable(number, (i+2)):
return True
i = i+6
return False
What does not sit well with me is the parse_oddeven_number(number) function. If new situations arrive then that list is going to be a long if, elif, else structure I rather not have. But I don't know what I can do about it.