473,762 Members | 8,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fastest way to loop through each digit in a number?

Hi,
If I have a lot of integers and want do something with each digit as
integer, what is the fastest way to get there?

Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"

(Btw: What is the English term for this process; itemize? tokenize?
digitize? sequence?)

Some examples:

n = 12345

#1.
s = str(n)
for i in s:
d = int(i)
foo(d)

#2.
nl = map(int, str(n))
for d in nl:
foo(d)

#3.
nl = [int(x) for x in str(n)]
for d in nl:
foo(d)

Of those, I have, a bit surprised, found that #1 is the fastest, and
that #2 using map() is faster than #3 using list comprehension. I also
registered that that repr(n) is about 8% faster than str(n).

Are there faster ways? Is it possible to avoid casting types?

Thanks for all answers!

Jul 18 '05 #1
9 32647
In article <ss************ *************** *****@4ax.com>,
Rune Strand <rst@_nospam_.d rlug.org._nospa m_> wrote:
Hi,
If I have a lot of integers and want do something with each digit as
integer, what is the fastest way to get there?

Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"


Does it matter what order you process the digits, i.e. least-significant
first vs. most-significant first? If you can do least first, then you
might be best off doing something straight-forward like:

i = 12345
while i:
digit = i % 10
i = i / 10
print digit

although, with the new-style division, I'm not sure if you want / or //.
Jul 18 '05 #2
Rune Strand <rst@_nospam_.d rlug.org._nospa m_> writes:
You could try timing something like

while n:
n,d = divmod(n, 10)
foo(d)

That processes the digits in reverse order, of course.
Jul 18 '05 #3
Paul Rubin <http://ph****@NOSPAM.i nvalid> wrote:
You could try timing something like

while n:
n,d = divmod(n, 10)
foo(d)

That processes the digits in reverse order, of course.


Thanks!
It's faster! But Roy Smiths modulus (%) method is even faster. The
order does matter, but even when appending d to a list inside the loop
and reversing it when done, your methods are faster than my initial
groks ;-)
Jul 18 '05 #4

"Rune Strand" <rst@_nospam_.d rlug.org._nospa m_> wrote in message
news:ss******** *************** *********@4ax.c om...
Hi,
If I have a lot of integers and want do something with each digit as
integer, what is the fastest way to get there?

Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"

(Btw: What is the English term for this process; itemize? tokenize?
digitize? sequence?)

Some examples:

You might also look at

zero = ord('0')

and then ord(i)-zero in loop

tjr

Jul 18 '05 #5
n2 = n
while n2 > 0:
d = n2 % 10
n2 /= 10
foo(d)
Jul 18 '05 #6
Roy Smith <ro*@panix.co m> wrote:
In article <ss************ *************** *****@4ax.com>,
Rune Strand <rst@_nospam_.d rlug.org._nospa m_> wrote:
Hi,
If I have a lot of integers and want do something with each digit as
integer, what is the fastest way to get there?

Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"


Does it matter what order you process the digits, i.e. least-significant
first vs. most-significant first? If you can do least first, then you
might be best off doing something straight-forward like:

i = 12345
while i:
digit = i % 10
i = i / 10
print digit

although, with the new-style division, I'm not sure if you want / or //.


He'd surely want truncation, so I don't understand why he could possibly
want / (which in new-style division means true, non-truncating
division), it's surely gotta be //. divmod looks like it might be
better, but from some q&d timeit.py'ing, it seems this approach is
fastest (30% faster than divmod) if these semantics are OK (when i is 0
you get nothing rather than a single 0...) -- map(int, str(i)) is midway
in speed through these purely numeric approaches (with % and // vs with
divmod).
Alex

Jul 18 '05 #7
On Mon, 6 Sep 2004 02:32:46 -0400, "Terry Reedy" <tj*****@udel.e du>
wrote:
You might also look at

zero = ord('0')

and then ord(i)-zero in loop


Thanks! That seems like the fastest solution.
When looping through 1000000, I get these results:
ord : 4.703 (Terry Reedy)
divmod : 10.469 (Paul Rubin)
modulo : 7.625 (Roy Smith)
lst comp: 11.750
map : 9.062
str : 8.219

The modulo and divmod methods includes list.append(d) and
list.reverse() (list.append mapped to list_append).

Jul 18 '05 #8
;-) 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])

Jul 18 '05 #9
On Mon, 06 Sep 2004 04:56:54 +0200, Rune Strand <rst@_nospam_.d rlug.org._nospa m_> wrote:
Hi,
If I have a lot of integers and want do something with each digit as
integer, what is the fastest way to get there?
How many is "a lot" ? And what are the bounds on your integers' values? ;-)
Keep in mind that whatever you are computing, it is a mapping from imput to output,
and sometimes it pays to implement a subproblem literally as a mapping.
Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"
E.g., if you had a bazillion numbers that were all positive and five digits max,
then your fastest mapping from number to digit sequence would probably be a precomputed
list or tuple with data like (untested):

digitseqs = [[0],[1],[2],...[8],[9],[1,0],[1,1],[1,2]... [1,2,3,4,5],[1,2,3,4,6], ... [9,9,9,9,9]]

and then there would be no computation of the digits in

for d in digitseqs[number]:
foo(d)

If your numbers are bigger, you can still use the same technique, chunkwise, e.g.,
if you know you have positive 32-bit integers, that's 0<= number <= 1073741824

if number >= 1000000000:
foo(1)
number -= 1000000000
low5 = number % 100000
for d in digitseqs[number//100000]: foo(d)
for d in zdigitseqs[low5]: foo(d)

(zdigitseqs are all 5-digit sequences with leading zeroes included, [[0,0,0,0,0],[0,0,0,0,1], ...])

If your numbers are unbounded, you can still do something along these lines, but
numbers have to be _huge_ before you gain more than you lose in complication.
You could wrap the above in a function like def fooit(number, foo=foofunc): ...
but calls are relatively expensive in time, so you may want to forego the nicer style.

Obviously 100k lists of lists take a fair chunk of memory, and take a little time to
pre-compute, but it may pay off if you have REALLY "a lot" of input numbers ;-)

(Btw: What is the English term for this process; itemize? tokenize?
digitize? sequence?)

Some examples:

n = 12345

#1.
s = str(n)
for i in s:
d = int(i)
foo(d)

#2.
nl = map(int, str(n))
for d in nl:
foo(d)

#3.
nl = [int(x) for x in str(n)]
for d in nl:
foo(d)

Of those, I have, a bit surprised, found that #1 is the fastest, and
that #2 using map() is faster than #3 using list comprehension. I also
registered that that repr(n) is about 8% faster than str(n).

Are there faster ways? Is it possible to avoid casting types?

Thanks for all answers!

I haven't timed the above (or even tested it), but your gains (if any ;-) will depend on
what you can assume about your input data.

Regards,
Bengt Richter
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3055
by: David P. Jessup | last post by:
Well I have seen this posted before and haven't seen much in response. My application has to browse through various folders and find file names. Sometimes these folders can have thousands of files in them, and of course looping through each file to find the right one can take a bit of time. I'm using classic ASP and was wondering if there are any other methods available to speed up this process other than hardware upgrades. My...
8
2858
by: Hardrock | last post by:
I encountered some difficulty in implementing dynamic loop nesting. I.e. the number of nesting in a for(...) loop is determined at run time. For example void f(int n) { For(i=0; i<=K; i++) For(i=0; i<=K; i++)
10
2027
by: zahy[dot]bnaya[At]gmail[dot]com | last post by:
Hello all, Sorry for the stupid question, It's probably has a simple solution but I'm stuck on this for quite a while... I have this piece of code, I've numbered it for clarification. As far as I can see it's a nested loop, the first one is (1 to 5 ) and the inner one is (3 to 4) BUT when I debug it it looks like the inner loop is (3-5). why? there are no curly braces so I assumed the 3rd line for scope is only line 4 and the if scope...
30
9078
by: Chaos | last post by:
As my first attempt to loop through every pixel of an image, I used for thisY in range(0, thisHeight): for thisX in range(0, thisWidth): #Actions here for Pixel thisX, thisY But it takes 450-1000 milliseconds I want speeds less than 10 milliseconds
5
2546
by: eyoung | last post by:
I have a function to check a string to make sure it is 6 digites using the trigger onBlur="CkFrmt(this)" Problem is I've got 4 fields in a row...if I enter a wrong number in the first and hit tab I get the error message and my script tries to move the focus to the first item...but because I hit the tab the focus in already on the second item which does not contain a 6 digit value so I must kill the page. help! function CkFrmt(str) {
8
6562
by: Candace | last post by:
I am using the following code to pick off each digit of a number, from right to left. The number I am working with is 84357. So for the first iteration it should return the number 7 and for the second iteration it should return the number 5, and so on. But for some reason on the first iteration returns the expected results. Each subsequent iteration returns the number plus 1. In order words, when I run the program I am getting: 7, 6, 4, and...
52
6348
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible variations(combination of fields), - then act on each group in some way ...eg ProcessRs (oRs as RecordSet)... the following query will get me the distinct groups
2
27361
by: hikmaz | last post by:
I am trying to get the rightmost digits (%10) of a number (taken from the user) and store it into successive array locations and get rid of the rightmost digit (\10) to store the next and so on and so forth. For example, if the number entered by the user is 4321 then, int array = 1 int array = 2 int array = 3 int array = 4 int array = '\0' (End of array - when number == 0) This is the piece of code i...
12
3236
by: beatjunkie27 | last post by:
I am working on a class assignment called Pennies for Pay the object of the program is to receive input for number of days worked. This should be > 0 and <= 40. An example output is below and you will notice, the pay doubles each day. Pay: $.01 on day 1. Total Salary $.01 Pay: $.02 on day 2. Total Salary $.03 Pay: $.04 on day 3. Total Salary $.07 Pay: $.08 on day 4. Total Salary $.15
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9989
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9927
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7360
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5268
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3914
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.