473,320 Members | 1,828 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Inverse of int(s, base)?

Hi,

Is there an inverse function of int(s, base) where base
can be any number up to 36? I've searched the library
reference up and down, but haven't found anything.

For example, I need to work with base-24 numbers, which
can be parsed nicely with x = int(s, 24), but there
doesn't seem to be a way to convert integers back to
their base-24 representation as a string. (Of course,
I can define my own function in Python to do that, but
I wonder if there's a more efficient way.)

Best regards
Oliver

PS: This is what I'm using right now.

import string
str_digits = string.digits + string.ascii_lowercase

def str_base (x, base):
result = ""
while x:
result = str_digits[x % base] + result
x /= base
return result or "0"
print str_base(2065027084, 24) aj83kb4 int("aj83kb4", 24)

2065027084

--
Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 München
Any opinions expressed in this message may be personal to the author
and may not necessarily reflect the opinions of secnetix in any way.

"Clear perl code is better than unclear awk code; but NOTHING
comes close to unclear perl code" (taken from comp.lang.awk FAQ)
Jul 18 '05 #1
6 4245
ol**@secnetix.de wrote in message news:<2g***********@uni-berlin.de>...
Hi,

Is there an inverse function of int(s, base) where base
can be any number up to 36?
Yes, but for some reason it's not in the Python standard library.

....
PS: This is what I'm using right now.

import string
str_digits = string.digits + string.ascii_lowercase

def str_base (x, base):
result = ""
while x:
result = str_digits[x % base] + result
x /= base
The above line should be "x //= base", so it works under -Qnew.
return result or "0"


That works (for positive integers), but it might be more efficient to
not create a new string each time through the loop. An alternative
is:

def str_base(n, base=10):
if n == 0:
return '0'
isNegative = n < 0
if isNegative:
n = -n
result = []
while n > 0:
n, lastDigit = divmod(n, base)
result.append(str_digits[lastDigit])
if isNegative:
result.append('-')
result.reverse()
return ''.join(result)
Jul 18 '05 #2
da*****@yahoo.com (Dan Bishop) writes:
while x:
result = str_digits[x % base] + result
x /= base
The above line should be "x //= base", so it works under -Qnew.


Or just say:
x, r = divmod(x, base)
result = result + str_digits[r]
That works (for positive integers), but it might be more efficient to
not create a new string each time through the loop. An alternative is:

def str_base(n, base=10):

...

Similarly:

def str_base(n, base=10):
results = []
sign,n = ('','-')[n < 0], abs(n)
while n:
n, r = divmod(n, base)
results.append(str_digits[r])
results.reverse()
return sign + ''.join(results)
Jul 18 '05 #3
Paul Rubin <http://ph****@nospam.invalid> wrote:
da*****@yahoo.com (Dan Bishop) writes:
[...]
That works (for positive integers), but it might be more efficient to
not create a new string each time through the loop. An alternative is:

def str_base(n, base=10):

...

Similarly:

def str_base(n, base=10):
results = []
sign,n = ('','-')[n < 0], abs(n)
while n:
n, r = divmod(n, base)
results.append(str_digits[r])
results.reverse()
return sign + ''.join(results)


Cool, thanks both of you! Using divmod() is a good idea.

Is creating strings really that expensive in Python? I'm
surpised that you're saying that modifying a list and then
calling reverse() and join() is more efficient. I thought
that the overhead of compound objects such as lists is
more expensive than creating strings, which I thought where
rather "cheap and simple".

I work with strings a lot (in scripts for administration,
CGI programs etc.). And since strings are immutable, I
often have to create new ones. Now do you suggest I should
reconsider my approach and rather try to work with lists in
general, and only convert them back to strings for output
at the very end?

Best regards
Oliver

--
Oliver Fromme, secnetix GmbH & Co KG, Oettingenstr. 2, 80538 Munich
Any opinions expressed in this message may be personal to the author
and may not necessarily reflect the opinions of secnetix in any way.

(On the statement print "42 monkeys" + "1 snake":) By the way,
both perl and Python get this wrong. Perl gives 43 and Python
gives "42 monkeys1 snake", when the answer is clearly "41 monkeys
and 1 fat snake". -- Jim Fulton
Jul 18 '05 #4
> Is there an inverse function of int(s, base) where base
can be any number up to 36?


How about this?

)esab ,s(tni

:-)
Jul 18 '05 #5
Oliver Fromme <ol**@secnetix.de> writes:
Is creating strings really that expensive in Python? I'm
surpised that you're saying that modifying a list and then
calling reverse() and join() is more efficient. I thought
that the overhead of compound objects such as lists is
more expensive than creating strings, which I thought where
rather "cheap and simple".


Actually, for these int conversions (unless they're large long ints)
it's no big deal. The concern is when you're building up a long
string (say, a 10 kilobyte html page) by concatenating a lot of short
strings. When you say "a = a + b" the cost is proportional to
len(a+b), since that many chars must get copied around. In the
extreme case, suppose you build up a 10k web page one character at a
time:

for c in get_next_char():
page = page + c

The first iteration copies 1 character, the next iteration copies 2
chars, the next one 3 chars, etc. So the total amount of copying is
1+2+3+...+10000, which is around 50 million. In general it's O(N**2)
where N is the number of concatenations.

By comparison, when you append something to a list, the cost is
usually constant. There's extra space in the list for appending, so
nothing gets copied (if there's no extra space left, then stuff does
get copied and more space is allocated). So
for c in get_next_char():
page.append(c)
is much more efficient than string concatenation. At the end, you do
all the concatenation in one step with ''.join(page).

See also the StringIO and cStringIO library modules for possibly
preferable ways to do this.
Jul 18 '05 #6
Paul Rubin wrote:
Oliver Fromme <ol**@secnetix.de> writes:
Is creating strings really that expensive in Python? I'm
surpised that you're saying that modifying a list and then
calling reverse() and join() is more efficient. I thought
that the overhead of compound objects such as lists is
more expensive than creating strings, which I thought where
rather "cheap and simple".

Actually, for these int conversions (unless they're large long ints)
it's no big deal. The concern is when you're building up a long
string (say, a 10 kilobyte html page) by concatenating a lot of short
strings. When you say "a = a + b" the cost is proportional to
len(a+b), since that many chars must get copied around. In the
extreme case, suppose you build up a 10k web page one character at a
time:

[snip]

This is a good time to remind newbies that the root of
all evil lies in premature optimization (attributed to
Donald Knuth).

You could do worse than read Guido's anecdote:
http://www.python.org/doc/essays/list2str.html

Then, read Joel's discussion of "Shlemiel the painter's
algorithm":
http://www.joelonsoftware.com/articl...000000319.html

And an example of it here:
http://lambda.weblogs.com/discuss/msgReader$3130
(see one of the last reader's comments)

In conclusion: if you are absolutely positive that you
are only going to be adding together a few short
strings, then you gain much readability by just adding
together short strings. But if you are going to be
adding together lots of long strings, use lists and
only convert to a string at the end.

--
Steven D'Aprano
Jul 18 '05 #7

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

Similar topics

1
by: Edward Arthur | last post by:
Hi, I'm trying to convert a string to an unsigned long long int. % /tmp/long str 0x20000 base 16 decimal 131072 hex 20000 str 0x1abcd8765
10
by: guidosh | last post by:
Hello, I'm trying to write a printf statement that sets the field width when printing a number. I'm using this: printf("%*", fieldwidth, num_to_print); However, I can't figure out how to...
6
by: Tony Tortora | last post by:
I am writing and add on application. The application uses Unique IDs and they are stored in Base 26 (ie 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ). I am having trouble reading the decimal value of a...
19
by: Robbie Hatley | last post by:
For your enjoyment, a function that expresses any integer with absolute value less-than-or-equal-to nine quintillion in any base from 2 to 36. (For larger bases, you could expand the "digit"...
30
by: ceeques | last post by:
Hi I am a novice in C. Could you guys help me solve this problem - I need to convert integer(and /short) to string without using sprintf (I dont have standard libray stdio.h). for...
12
by: andrew_nuss | last post by:
Hi, I have a template array class on T with specialization for bloat when T is void*. Thus when T is really an int*, my base ptr is physically a void** and needs to be converted to an int**. ...
5
by: Dennis Jones | last post by:
Hello, I have a couple of classes that look something like this: class RecordBase { }; class RecordDerived : public RecordBase {
8
by: per9000 | last post by:
Hi, I wanted to test to compile an application I build for .NET 2.0 in with the 1.1 C# compiler. I encountered difficulties since I had a List<myClass>. I found a list of what is new in .NET 2.0...
11
by: jyck91 | last post by:
// Base Conversion // Aim: This program is to convert an inputted number // from base M into base N. Display the converted // number in base N. #include <stdio.h> #include <stdlib.h>...
8
by: sdlt85 | last post by:
Hi, the program is asking the user for a number ant he base of the number, then it will convert the number to decimal. But is running right only with base 2, 3, 4, 5, 6, 7, 8 but if I try 16 it is...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.