This is the CodeEval problem #227 and I have solved it using Python 3 as implementation language.
Here is how I converted the samples in test cases:
def test_provided_1(self): self.assertEqual('Fake', solution('9999 9999 9999 9999')) def test_provided_2(self): self.assertEqual('Real', solution('9999 9999 9999 9993'))
The solution, even though it is pretty short, could be logically divided in three parts.
Extracting data from the provided string
numbers = [int(i) for i in line if i.isdigit()]I used a list comprehension to convert the input string in a list of integer. For each character in the line I check if it is a digit. If so, I convert it to integer and then I append it to the list.
Calculate the checksum
result = 0 for i in range(len(numbers)): result += numbers[i] if i%2 else numbers[i] * 2I applied the rule. Looping on all numbers, add to the result the current value if it is in odd position, or its square value otherwise.
Return the result
return 'Fake' if result % 10 else 'Real'It is natural for me using here a conditional expression, given my background as C programmer where a ternary operator (?:) would have done the job.
If the division by ten gives a remainder, aka result modulo ten is not zero, we have a fake credit card, otherwise the checksum is passed.
Solution accepted by CodeEval, so I pushed test case and python script to GitHub.