What is the best practice for iterating over an integer in Python? I find that I need to do so often, typically with verbose results. For example, here are two functions I wrote for Project Euler problems:
def is_permutation_of(n, m):
""" Return True if n is a permutation of m, else False
"""
if len(str(n)) != len(str(m)):
return False
for d in str(n):
if d not in str(m):
return False
return True
And another:
def has_even_digit(n):
""" Return True if n has an even digit, else False
"""
evens = ['0', '2', '4', '6', '8']
for e in evens:
if e in str(n):
return True
return False
In addition to the verbosity, 1) there must be a computational expense associated with each type conversion and 2) it just feels completely inelegant. Is there another way of dealing with this issue? Am I going about these functions in entirely the wrong way, i.e. should I not have to ever iterate over an integer?
Thanks for any help.
I prefer my variant instead of your
is_permutation_of:And I think this is better for
has_even_digitOr, even use a tuple rather than a set:
Edit
From the comment thread, I thing you are looking for something like this:
This does not work because integers do not support iteration in Python. Additionally, there is no real need have something like an integer iteration since it is so idiomatic and easy to do it with strings.
Here is a Python framework to do it with strings but produce single integer digit:
If you want the same number right to left:
Compare those two simple cases with doing it with actual math with the integer or long:
It is really a lot easier to use strings and probably faster. If you need blazing speed, do it in C.