473,698 Members | 2,158 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
21 2149
Andrea Griffini wrote:
roman = lambda x: "".join(["".join(map(lam bda c: "IVXLCDM"[int(c)
+2*N],"/0/00/000/01/1/10/100/1000/02".split("/")[x//10**N % 10]))
for N in (3, 2, 1, 0)])


This rocks!! I'm still trying to understand how it works though :)
--Irmen
Jul 18 '05 #21
On Mon, 01 Nov 2004 11:06:24 +0100, Irmen de Jong
<irmen@-NOSPAM-REMOVETHIS-xs4all.nl> wrote:
Andrea Griffini wrote:
roman = lambda x: "".join(["".join(map(lam bda c: "IVXLCDM"[int(c)
+2*N],"/0/00/000/01/1/10/100/1000/02".split("/")[x//10**N % 10]))
for N in (3, 2, 1, 0)])


This rocks!! I'm still trying to understand how it works though :)


The idea is to use the pattern

"", "0", "00", "000", "01", "1", "10", "100", "1000", "02"

where every character listed above is an offest in

"IVX", "XLC", "CDM", "M??"

For example applying the offsets to the first group you get:

"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"

i.e. the roman numbers for 0..9; and applying it to the second

"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",

i.e. 0, 10, 20, ... 90.

I just used "split" and string indexing instead of regular
lists because the code becomes smaller (and more readable
than a mess of quotes and commas).

The rest is a loop on the thousands, the hundreds, the tens
and the units of the number and the joins needed to glue
all the pieces into a resulting string.

Andrea

Jul 18 '05 #22

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

Similar topics

10
2670
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
1397
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 tables has 1.500 records.
0
1437
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 (you can cut/paste the text somewhere else), then try cutting/pasting the control(s) again. Then...
13
3253
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. Here is the code: #include <iostream>
3
1549
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
5747
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
19333
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
2036
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
2659
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" }; System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(@"C: \test.dbf", true,...
6
19190
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
8683
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
9031
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
8901
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,...
0
8871
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6528
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
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.