python equivalent to haskells iterate.

Nick Coghlan ncoghlan at iinet.net.au
Fri Feb 4 07:55:02 EST 2005


Graeme Caldwell wrote:
> What this does is takes as a paramter a decimal integer and converts
> it to a sequence in which each member is numeral from each position in
> the integer.

For this specific problem, the builtin 'str' is your best bet:

   digit_list = map(int, str(val))

(If you only want to display the digits, you can use list(str(val)) to leave 
them as strings rather than converting back to an int)

However, that doesn't really fit with the general 'iterate' question you were 
asking. For that, something like a generator function is likely to help:

   def digits(val):
     if val:
       while val:
         val, digit = divmod(val, 10)
         yield digit
     else:
       yield 0

   digit_list = list(reversed(list(digits(val))))

Basically, I think the 'yield' keyword and generator functions are likely what 
you are looking for when it comes to easily building iterators.

However, continuing on with the attempt to write Haskell in Python, making the 
generator function 'dumber' by eliminating its knowledge of the termination 
condition gets us closer to the original:

   from itertools import takeWhile

   def next_digit(val):
     while 1:
       val, digit = divmod(val, 10)
       yield digit

   digit_list = list(reversed(list(
                      takewhile(lambda digit: digit, next_pair(val)))))


For cases where you don't need to do an assignment each time through the loop 
(e.g. by dividing by progressively larger multiples of 10 instead of using 
repeated division), you can ditch the function and use a generator expression 
instead:

   from itertools import takewhile, count
   digit_list = reversed(
                  list(
                    takewhile(
                      lambda digit: digit,
                      (((val // (10 ** i)) % 10) for i in count())
                    )
                  )
                )

Usually you're going to be better served by making the generator function 
smarter if you're going to be writing one anyway, though.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list