Simplified program by using some pattern matching.
Problem solved using a list comprehension.