Python and Ruby have been so hyped in the .NET community for the last couple of months so I decided to attempt to solve this problem using IronPython – originally inspired by a Linq solution posted by Octavio Hernandes.
Find a number consisting of 9 digits in which each of the digits from 1 to 9 appears only once. This number must also satisfy these divisibility requirements:
1.The number should be divisible by 9.
2.If the rightmost digit is removed, the remaining number should be divisible by 8.
3.If the rightmost digit of the new number is removed, the remaining number should be divisible by 7.
4.And so on, until there’s only one digit (which will necessarily be divisible by 1).
I was amazed when I first saw how easy Linq could solve this problem. But … then I found Python. Now – check this out:
def validate(n, denominator):
if denominator == 1: return True
if int(n) % denominator != 0: return False
return validate(n[:len(n)-1], denominator - 1)
for x in IronPython.Modules.PythonIterTools.permutations("123456789"):
joined = ''.join(x)
if validate(joined, 9): print(joined)
10 lines – slam dunk! Since this is my first Python code lines ever, I apologize to the Python purists in advance – but hey, I just had to advocate this🙂 And yes, it does perform.
For a comparison between Linq and C++ solutions please check out my earlier block post on this. Remember to go though the comments where an F# solution is also suggested.