Fastest way to loop through each digit in a number?

Rune Strand rst at _nospam_.drlug.org._nospam_
Mon Sep 6 11:37:30 EDT 2004


;-) Somtimes the solition is too obvious...  faster than using ord()
is to look up the value in a map:

dictmap = {
    '0' : 0,
    '1' : 1,
    '2' : 2,
    '3' : 3,
    '4' : 4,
    '5' : 5,
    '6' : 6,
    '7' : 7,
    '8' : 8,
    '9' : 9
    }

def each_dig_in_num(n):
    dm = dictmap   #faster if local
    s = repr(n)          #repr is faster than str
    for char in s:
        foo(dm[char])




More information about the Python-list mailing list