473,569 Members | 2,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"number-in-base" ``oneliner''

I hesitate a bit to post this, but... on the Italian Python NG, somebody
was asking whether there was any way to convert an integer number x into
a string which represents it in an arbitrary base N (given a sequence
with a len of N that gives the digits to use) as "a single expression".

I haven't found a really general way, much less a clear one, but, the
best I have so far is...:

def number_in_base( x, N, digits, maxlen=99):
return '-'[x>=0:] + (
(x and ''.join([digits[k%N] for i in range(maxlen)
for k in [abs(x)//N**i] if k>0])[::-1]
) or digits[0])

Besides the lack of clarity, the obvious defect of this approach is that
darned 'maxlen' parameter -- but then, since I can have only a 'for',
not a 'while', in a list comprehension or generator expression, and I
don't think recursion qualifies as 'a single expression'...:-(

Anyway, improvements and suggestions welcome, thanks!
Alex
Jul 18 '05 #1
21 2130
On Fri, 29 Oct 2004 23:58:47 +0200, al*****@yahoo.c om (Alex Martelli) wrote:
I hesitate a bit to post this, but... on the Italian Python NG, somebody
was asking whether there was any way to convert an integer number x into
a string which represents it in an arbitrary base N (given a sequence
with a len of N that gives the digits to use) as "a single expression".

I haven't found a really general way, much less a clear one, but, the
best I have so far is...:

def number_in_base( x, N, digits, maxlen=99):
return '-'[x>=0:] + (
(x and ''.join([digits[k%N] for i in range(maxlen)
for k in [abs(x)//N**i] if k>0])[::-1]
) or digits[0])

Besides the lack of clarity, the obvious defect of this approach is that
darned 'maxlen' parameter -- but then, since I can have only a 'for',
not a 'while', in a list comprehension or generator expression, and I
don't think recursion qualifies as 'a single expression'...:-(

Anyway, improvements and suggestions welcome, thanks!

Maybe something useful in this? Not very tested (and not terribly clear either ;-)
def number_in_base( x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter(
... lambda qr=[abs(x),0]:qr[0] and (
... qr.__setslice__ (0,2,divmod(qr[0],N)) or digits[qr[1]])
... , 0)][::-1])
... number_in_base( 126 ,2,'0123456789A BCDEF') '1111110' number_in_base( 126 ,8,'0123456789A BCDEF') '176' number_in_base( 126 ,16,'0123456789 ABCDEF') '7E' number_in_base( 1 ,16,'0123456789 ABCDEF') '1' number_in_base( 0 ,16,'0123456789 ABCDEF') '0' number_in_base(-126 ,16,'0123456789 ABCDEF') '-7E' number_in_base(-126 ,2,'0123456789A BCDEF') '-1111110'

Even less tested, and using a list subtype with overridden next to do the same:
def number_in_base( x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in type('',(list,) ,{
... '__iter__':lamb da s:s, 'next':lambda s:(
... s[0] is 0 and iter([]).next() or
... s.__setslice__( 0,2,divmod(s[0],N)) or digits[s[1]])
... })([abs(x),0])][::-1])
... number_in_base(-126, 8, '01234567') '-176' number_in_base(-126, 2, '01') '-1111110' number_in_base( 126, 2, '01') '1111110' number_in_base( 0 , 2, '01') '0' number_in_base( 1 , 2, '01')

'1'

;-)

Regards,
Bengt Richter
Jul 18 '05 #2
On Fri, 29 Oct 2004 23:58:47 +0200, al*****@yahoo.c om (Alex Martelli) wrote:
I hesitate a bit to post this, but... on the Italian Python NG, somebody
was asking whether there was any way to convert an integer number x into
a string which represents it in an arbitrary base N (given a sequence
with a len of N that gives the digits to use) as "a single expression".

I haven't found a really general way, much less a clear one, but, the
best I have so far is...:

def number_in_base( x, N, digits, maxlen=99):
return '-'[x>=0:] + (
(x and ''.join([digits[k%N] for i in range(maxlen)
for k in [abs(x)//N**i] if k>0])[::-1]
) or digits[0])

Besides the lack of clarity, the obvious defect of this approach is that
darned 'maxlen' parameter -- but then, since I can have only a 'for',
not a 'while', in a list comprehension or generator expression, and I
don't think recursion qualifies as 'a single expression'...:-(

Anyway, improvements and suggestions welcome, thanks!

Maybe something useful in this? Not very tested (and not terribly clear either ;-)
def number_in_base( x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter(
... lambda qr=[abs(x),0]:qr[0] and (
... qr.__setslice__ (0,2,divmod(qr[0],N)) or digits[qr[1]])
... , 0)][::-1])
... number_in_base( 126 ,2,'0123456789A BCDEF') '1111110' number_in_base( 126 ,8,'0123456789A BCDEF') '176' number_in_base( 126 ,16,'0123456789 ABCDEF') '7E' number_in_base( 1 ,16,'0123456789 ABCDEF') '1' number_in_base( 0 ,16,'0123456789 ABCDEF') '0' number_in_base(-126 ,16,'0123456789 ABCDEF') '-7E' number_in_base(-126 ,2,'0123456789A BCDEF') '-1111110'

Even less tested, and using a list subtype with overridden next to do the same:
def number_in_base( x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in type('',(list,) ,{
... '__iter__':lamb da s:s, 'next':lambda s:(
... s[0] is 0 and iter([]).next() or
... s.__setslice__( 0,2,divmod(s[0],N)) or digits[s[1]])
... })([abs(x),0])][::-1])
... number_in_base(-126, 8, '01234567') '-176' number_in_base(-126, 2, '01') '-1111110' number_in_base( 126, 2, '01') '1111110' number_in_base( 0 , 2, '01') '0' number_in_base( 1 , 2, '01')

'1'

;-)

Regards,
Bengt Richter
Jul 18 '05 #3
On Sat, 30 Oct 2004 06:07:23 GMT, bo**@oz.net (Bengt Richter) wrote:
[...]
Maybe something useful in this? Not very tested (and not terribly clear either ;-)
def number_in_base( x, N, digits): ... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter(
... lambda qr=[abs(x),0]:qr[0] and (
... qr.__setslice__ (0,2,divmod(qr[0],N)) or digits[qr[1]])
... , 0)][::-1])
...


Alternatively, a little more compactly (though I feel guilty about the -1 ;-):
def number_in_base( x, N=10, digits='0123456 789ABCDEF'): ... return '-'[:x<0] + ''.join(list(it er(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0) and (
... qr.__setslice__ (0,2,divmod(qr[0],N)) or digits[qr[1]]), False))[::-1])
... number_in_base( 126,2,'01') '1111110' number_in_base( 126, 8,'01234567') '176' number_in_base(-126, 8,'01234567') '-176' number_in_base( -1, 2,'01234567') '-1' number_in_base( 1, 2,'01234567') '1' number_in_base( 0, 2,'01234567')

'0'

Regards,
Bengt Richter
Jul 18 '05 #4
<ex*****@divmod .com> wrote:
...
def number_in_base( x, N, digits, maxlen=99):
return '-'[x>=0:] + (
(x and ''.join([digits[k%N] for i in range(maxlen)
for k in [abs(x)//N**i] if k>0])[::-1]
) or digits[0])
... range(maxlen) can be replaced with range(int(math. log(x) / math.log(N)) + 1).

Right! I had missed that because I was focusing on builtin names only.
Thanks!

Also, and perhaps you are already aware, number_in_base( x, 1, '0')
Yes, I was aware that the pre condition N>=2 (as well as other
preconditions, such as len(digits) >= N) are not checked; sorry for not
making that clear.
doesn't produce the correct output with the above algorithm, although I
believe it will if you switch to using math.log().


With math.log it raises a ZeroDivisionErr or -- arguably more correct
than a bunch of 0's, yes. It's interesting that the math.log
application does catch such errors as N<2;-).
Alex
Jul 18 '05 #5
On Sat, 30 Oct 2004 07:48:34 GMT, bo**@oz.net (Bengt Richter) wrote:
On Sat, 30 Oct 2004 06:07:23 GMT, bo**@oz.net (Bengt Richter) wrote:
[...]
Maybe something useful in this? Not very tested (and not terribly clear either ;-)
>>> def number_in_base( x, N, digits):

... return x==0 and digits[0] or '-'[:x<0] + ''.join([d for d in iter(
... lambda qr=[abs(x),0]:qr[0] and (
... qr.__setslice__ (0,2,divmod(qr[0],N)) or digits[qr[1]])
... , 0)][::-1])
...


Alternativel y, a little more compactly (though I feel guilty about the -1 ;-):
def number_in_base( x, N=10, digits='0123456 789ABCDEF'): ... return '-'[:x<0] + ''.join(list(it er(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0) and (
... qr.__setslice__ (0,2,divmod(qr[0],N)) or digits[qr[1]]), False))[::-1])
...


Yet another, prefixing digits instead of joining reversed list:
def number_in_base( x, N=10, digits='0123456 789ABCDEF'): ... return '-'[:x<0]+reduce(lambda s,c:c+s, iter(lambda qr=[abs(x),-1]: (qr[0] or qr[1]<0)
... and (qr.__setslice_ _(0,2,divmod(qr[0],N)) or digits[qr[1]]), False))
... number_in_base( 0 , 2, '01') '0' number_in_base( 1 , 2, '01') '1' number_in_base( 126, 2, '01') '1111110' number_in_base(-126, 2, '01')

'-1111110'

Regards,
Bengt Richter
Jul 18 '05 #6
On Fri, 29 Oct 2004 23:34:42 GMT, ex*****@divmod. com wrote:
range(maxlen) can be replaced with range(int(math. log(x) / math.log(N)) + 1).
Log accepts the base as second argument.

def number_in_base( x, N=10, digits="0123456 789ABCDEF"):
return '-'[x>=0:]+"".join(
[digits[abs(x)/N**i%N]
for i in xrange(1+int(ma th.log(abs(x)+1 ,N)))
if N**i<=abs(x)][::-1]) or digits[0]
Also, and perhaps you are already aware, number_in_base( x, 1, '0') doesn't produce the correct output with the above algorithm, although I believe it will if you switch to using math.log().


It doesn't handle roman numerals either... but so ?
You can't count using base 1 with positional systems.

Andrea
Jul 18 '05 #7
On Sat, 30 Oct 2004 12:12:36 +0000, Andrea Griffini wrote:
You can't count using base 1 with positional systems.


Well, you can, sort of. You end up with the integers, obviously, and the
result has a rather striking resemblance to the modern foundations of
number theory, in which there is only one number, 0, and the "increment"
function which returns a number one larger. If you want three, it is
expressed increment(incre ment(increment( 0))), which is rather similar to
the base-1 number "111".

Zero in this system would probably be a null string, making increment this:

def increment(numbe r):
return "1" + number

(And abracadabra, I'm back on topic for the newsgroup, albeit tenuously :-) )

Some people say base 2 is the most natural base in the universe. But you
can certainly make a claim for base 1, based on its correspondence to
number theory, from which we build the rest of math. (Most people never
dig this deep; it was one of my favorite classes in Comp. Sci., though,
and we're probably the only people other than mathematicians to offer the
course.)
Jul 18 '05 #8
Hi all,

warning: off topic nitpicking below!

Jeremy Bowers said unto the world upon 2004-10-30 13:29:
On Sat, 30 Oct 2004 12:12:36 +0000, Andrea Griffini wrote:
You can't count using base 1 with positional systems.

Well, you can, sort of. You end up with the integers, obviously, and the
result has a rather striking resemblance to the modern foundations of
number theory, in which there is only one number, 0, and the "increment"
function which returns a number one larger. If you want three, it is
expressed increment(incre ment(increment( 0))), which is rather similar to
the base-1 number "111".


I take it you didn't mean 0 was the only number, but rather the only
primitive number. (Alternatively " '0' is the only individual constant"
in the cant I prefer.)

I am also surprised to see "increment" -- I come to that material with
working in Philosophy of Mathematics and Logic, but almost every
presentation I have ever seen uses "successor" . (I'm going off of
philosophical and mathematical logic presentations.)

I do so wish that terminology is the whole area would just stabilize
already!

Zero in this system would probably be a null string, making increment this:

def increment(numbe r):
return "1" + number

(And abracadabra, I'm back on topic for the newsgroup, albeit tenuously :-) )

Some people say base 2 is the most natural base in the universe. But you
can certainly make a claim for base 1, based on its correspondence to
number theory, from which we build the rest of math. (Most people never
dig this deep; it was one of my favorite classes in Comp. Sci., though,
and we're probably the only people other than mathematicians to offer the
course.)


I've never taken a single comp. sci. course, so I will both claim and
commit disciplinary bias: serious undergrad logic/foundations of maths
courses do happen in Philosophy, too :-)

On the other hand, I'm a bit surprised that these things get taught in
comp. sci. This past summer when teaching Intro to Logic, I encountered
at least one fourth-year comp. sci. student who had no idea what an
axiomatic system was :-|

print "We now return you to your usual programing"

Best to all,

Brian vdB

Jul 18 '05 #9
On Sat, 30 Oct 2004 16:06:04 -0400, Brian van den Broek wrote:
I take it you didn't mean 0 was the only number, but rather the only
primitive number. (Alternatively " '0' is the only individual constant"
in the cant I prefer.)
*shrug* Can't say I get worked up over the difference there. Regardless,
you "can't" write "3". (Of course you can define it, but that's true of
everything.)
I am also surprised to see "increment" -- I come to that material with
working in Philosophy of Mathematics and Logic, but almost every
presentation I have ever seen uses "successor" . (I'm going off of
philosophical and mathematical logic presentations.)
Yeah, that would be right. Couldn't recall the exact name.
number theory, from which we build the rest of math. (Most people never
dig this deep; it was one of my favorite classes in Comp. Sci., though,
and we're probably the only people other than mathematicians to offer the
course.)


I've never taken a single comp. sci. course, so I will both claim and
commit disciplinary bias: serious undergrad logic/foundations of maths
courses do happen in Philosophy, too :-)


Gonna nit pick myself here: "Most people". I think adding Philosophers and
dilettantes and the rare electrical engineer isn't likely to change the
"most".
On the other hand, I'm a bit surprised that these things get taught in
comp. sci. This past summer when teaching Intro to Logic, I encountered
at least one fourth-year comp. sci. student who had no idea what an
axiomatic system was :-|


Graduate level. And many of the grads hated it. There is a chasm between
the average Comp. Sci. student and the average professor; it isn't so bad
at the grad level but it is still there. I'm not sure if it's worse than
most disciplines, but I am inclined to believe it is, since Comp Sci
typically can't really work out if it is math or engineering (wide
consensus is that while there are scientific aspects to it, it probably
shouldn't have it in the name), and there are, in my experience, fairly
clean divisions of each student and professor into one camp or another. I
was one of the exceedingly rare students who could do both quite well, and
freely translate between them.
Jul 18 '05 #10

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

Similar topics

10
2663
by: Boštjan Jerko | last post by:
Hello ! I need to know if the result of math formula is nan (Not a number). How can I do that? Thanks, B.
2
1390
by: Gianluca_Venezia | last post by:
Talking about high number of record seem ridiculus, if this number is about 88.000 but when I open a form, linked via ODBC to a MYSQL table, the open and the use of that form is slow, and very slow if the form has combo controls. I have a order form, and a combo control for custemer codes. Order table counts 88.000 records, customer...
0
1434
by: gahagan | last post by:
If you encounter this error, most likely one of the controls you're trying to cut/paste is a combo box with a longer-than-average 'Row Source' value. That, apparently, is the problem. Shorter Row Source values don't seem to be a problem. (I don't have time to figure out at what length the error triggers.) Workaround: Remove the Row Source...
13
3227
by: Fao | last post by:
Hello, I am having some problems with inheritance. The compiler does not not return any error messages, but when I execute the program, it only allows me to enter the number, but nothing else happend. I think the problem may be in my input function or in the main function. If anyone out there can help me it woul be greatly appreciated. ...
3
1539
by: Nevyn | last post by:
How do I do that? Turning the layout from the customerID-number "10205" into looking like "10 205"? I've just incresed it from four digits to five, and it looks like this: lsvItem.SubItems(1) = Right("0000" & CStr(rs!customerID), 5), but how do I affect the layout?
4
5744
by: zensunni | last post by:
Here's what my code looks like: ======================================= Set RS = Server.CreateObject("ADODB.Recordset") RS.Open "Table", objConn, 1, 3, 2 If Len(Request.Form("AreaID1")) > 0 Then RS("AreaID1") = Request.Form("AreaID1") End If If Len(Request.Form("AreaID2")) > 0 Then
2
19298
by: mktselvan | last post by:
Hi, Existing running oracle application 11i (11.5.8) Database version is 8.1.7.4 There is any command / way to know the number of concurrent users for this application. select SESSIONS_MAX, SESSIONS_WARNING,
4
2028
by: ravi | last post by:
Hi all, I written and compiled a c++ program using g++ no errors or warning are reported. But when I run it , reporting an error : ERROR: Wrong magic number. What is the reason for this error? anybody had an idea ?
4
2653
by: ajmastrean | last post by:
I cannot get any (hex) number in the "0x80"-"0x89" range (inclusive) to write properly to a file. Any number in this range magically transforms itself into "0x3F". For instance, debugging shows that "0x83" = UInt16 "131" and that converts to Char (curly) "f". Any information would be helpful. String hexNum = { "79", "80", "89", "90" };...
6
19174
by: nickyazura | last post by:
hello, i would like to know how to do numbering format for "0000" where each time it will generate 0001,0002,0003 and so on untill 9999. counter = "0000" counter = counter + 1
0
7703
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...
0
7618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7926
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. ...
0
7983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5514
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...
0
3657
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...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2117
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
0
946
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...

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.