[Tutor] built in functions int(),long()+convert.base(r1,r2,num)

cino hilliard hillcino368@hotmail.com
Fri Jun 20 03:40:02 2003


This is a multi-part message in MIME format.

------=_NextPart_000_42a_6aca_5f1d
Content-Type: text/plain; format=flowed


Hi Jeff, et al,
Thank for your input and all your work in this list.
I have comments below. Some of the examples will use convert.py and base3.py
Please take no offense at my remarks as I am trying to learn. If i have made 
an unsupportable
claim then a correction of that will reinforce my learning.

Python is a great language and I love not having to fiddle with the variable 
declarations and ; endings
etc that infect other languages like BCX(which I like a lot) Pari script, 
SAS,  and C.   :--)


>From: "Jeff Shannon" <jeff@ccvcorp.com>
>To: tutor@python.org
>CC: cino hilliard <hillcino368@hotmail.com>
>Subject: Re: [Tutor] built in functions int(),long()
>Date: Thu, 19 Jun 2003 11:37:51 -0700

>No, because an integer doesn't have a base associated with it, only the 
>representation does.
Which integer? Python integer sure does. It is base 10.
>
>How many asterisks is this?    *  *  *  *  *  *  *  *  *  *  *  *  *
  How many cows  is this?       cowcowcowcowcowcowcowcowcowcowcowcowcow
>
>"13" in base 10
>"15" in base 8
>"D" in base 16
I challenge you to print "D" asterisks
>"11" in base 12
>"31" in base 4
>"1101" in base 2
>"XIII" in Roman ;)
In fact, I challenge you to print out the *'s for any base other than 10.
obviously it will be *  *  *  *  *  *  *  *  *  *  *  *  * the same as 
above.
Ain't no way around it. It is a matter of having. How many *'s do you have 
in base 4? well lets see.
since you say 31 then 4*3^1 = 1*3^0 = 13 so I have 13 base 10. Certainly, it 
would be a barter
nightmare if farmers represented a different representation of scratches on 
a stone for the same
number of cows in their possession. Conceptual amounts would only be 
attained if an agreed
upon "base" base were chosen. Lets say that base is 17. then  the above 
values except Roman, convert to D in my program. Until we do this we will be 
in chaos not much different to the cardinal
system of some, few, many, very few,zilch  etc.


>
>I use quotes because these are symbols (strings) representing something 
>else (a number) -- but they all represent the *same* number.  A "pure" 
>number doesn't have a base associated with it --
What is a pure number? Pure base 62 is 6176790 base 10.
>the base describes the representation, not the number itself.  The

123 base 10 = 1*10^2+2*10^1+3*10^0;123 base 62 =1*62^2+2*62^1+3*62^0 = 3971 
base 10;
What do you mean? With out a base we cannot express the number. The above 
example obviously
implies that the base x describes the polynomial number = 
a_nx^n+a_n-1x^(n-1)...+a_0x^0.

>int() function (and atoi(), which is really the same thing) will convert a 
>representation (which has a base associated with it) to the underlying 
>number (which has no base).

Balony. The number converted to is base 10 period. Sure it's binary 
internally but to the
viewer it is decimal. That is all the function can do in terms of base 
conversion. I knew that.
The issue is the vague definition which by the way is not life threatning. 
It just ain't clear to me. That
was my point. Read the thing carefully and you will see it too. Don't keep 
snipping it when you try to defend it. In uppercase BELOW I give a more 
precise definition of what python actually does.
Like I said earlier, it is not life threatning.

atoi( s[, base])

Deprecated since release 2.0. Use the int() built-in function.
Convert string s to an integer in the given base. The string must consist of 
one or more digits, optionally

CONVERT A STRING S IN A GIVEN BASE TO AN INTEGER IN BASE 10. Examples,
>>>int('JEFFSHANNON',36)                         #Lowercase converts to 
>>>upper
70932403861357991L                                  #watch out for the L in 
convert.py as it uses it as a digit!

c:\Python23>python base3.py 36 10 JEFFSHANNON
70932403861357991

c:\Python23>python base3.py 10 36 70932403861357991
JEFFSHANNON

c:\Python23>python base3.py 62 10 JeffShannon     #Here we use base 62 to 
allow lowercase.
16497269374220967401

Notice we dont have to put the value string in quotes.

[snip atoi]



int( x[, radix])

Convert a string or number to a plain integer. If the argument is a string, 
it must contain a possibly

CONVERT A STRING OR NUMBER IN BASE RADIX TO A PLAIN INTEGER IN BASE 10. NOTE 
THAT YOU
CANNOT GO THE OTHER WAY - FOR EXAMPLE CONVERT STRING BASE 10 TO BASE 2 IS 
NOT
SUPPORTED.

signed decimal number representable as a Python integer, possibly embedded 
in whitespace; this
behaves identical to string.atoi(x[, radix]). The radix parameter gives the 
base for the conversion and


THE RADIX IS THE BASE WE ARE CONVERTING THE STRING FROM. THE RESULT WILL 
ALWAYS
BE A PYTHON  INTEGER IN BASE 10. YOU CANNOT CONVERT TO ANY OTHER BASE THAN 
10.


Maybe any integer in the range [2, 36], or zero. If radix is zero, the 
proper radix is guessed based on
Hmm.., Example of 0 radix errors out
SyntaxError: invalid syntax
>>>int('JEFFSHANNON',0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): JEFFSHANNON
>>>
It appears that a sufficient magnitude in radix is required to avoid errors. 
Radix 29 takes you to letter S,
The largest letter in JEFFSHANNON. Then radix 29-36 will not error on that 
input.

the contents of string; the interpretation is the same as for integer 
literals. If radix is specified and x is
not a string, TypeError is raised. Otherwise, the argument may be a plain or 
long integer or a floating
point number. Conversion of floating point numbers to integers truncates 
(towards zero). If the
argument is outside the integer range a long object will be returned 
instead.

>What has you confused is that Python, when asked to show you an
I am not confused at what python does. That is obvious. I am confused in how 
your manual
describes it. Ii know what it does. It just doesn't do what you say it is 
supposed to do
the way I read the definition.


>integer, will automatically convert that integer into base 10 for display. 
>However, that's a feature of the display, not of the integer itself -- it 
>just so happens that for humans, base 10 is easiest to read, so Python 
>accommodates us (unless we specifically

Balony. It is easiest to read because we were taught that way. Not because 
we are humans.

>request otherwise, through the use of hex() or similar functions).  Of 
>course, internally the computer will store all integers in binary format 
>(base 2), because that's the way that computers are wired.
>
>>Question. How can I get convert.base(r1,r2,str) without having to type the 
>>quotes for the string?
>>Eg., convert(16,10,FFFF) instead of convert(16,10,"FFFF") = 65535 ?
>
>You can't, because the Python parser would have way of knowing
Of course you can. Change python >>> CONSOLE source to do it like dos. See 
my examples above.

>what's intended -- is FFFF a string? A hexidecimally-represented
what else could FFFF mean in a hex to decimal conversion? Of course it is a 
string to convert to decimal.
it could be represented as a list [15,15,15,15]. In fact the whole 
conversion process could be done this
way albiet a little awkward to read. This way you would never run out of 
characters as you increased the radix.

>integer? A variable?  As a matter of fact, the last is exactly how the 
>parser sees this -- it looks at FFFF as a variable name, and
this is dumb. It should look at it as a string. would require some thinking 
but it should be doable.
Try the dos example below. Obviouslt python is reading the stdin base3.py 
and passing the command
tail to variables r1,r2 and num. Python.exe is smart. it is the >>> console 
that doesn't understand.

c:\Python23>python base3.py 36 10 JEFFSHANNON         Look mom, no quotes.
70932403861357991

perhaps a replaceable parameter scheme def .base(10,16,%num%) means the 
expression entered
into the var num is to read as 'contents of num' This is just me musing. If 
python had var declaration
requirements this would not benecessary but don't do that! I will live with 
convert.base(16,10,'FFFF')!
In fact it is accademic. I like the dos command line approach better. The 
only caveat is that >>> will
evaluate expressions. The current dos version does not. Example
>>>convert.base(10,16,2**256-1)                 See Mom, No quotes here 
>>>either!
0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
>>>
>>>int('0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',16)
115792089237316195423570985008687907853269984665640564039457584007913129639935L
>>>
>>>2**256-1
115792089237316195423570985008687907853269984665640564039457584007913129639935L

>>>convert.base(10,16,115792089237316195423570985008687907853269984665640564039
457584007913129639935)
0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF   #the 
leading 0 Hmmm...
>>>
starts after 2^64+1 ?
>attempts to look up a value for it (probably resulting in a NameError).  
>You could, in this case, specifically designate that it's a hexidecimal 
>number by typing it as 0xFFFF -- but then, a
Similar to my thought above but do it to the variable in the function 0xnum
>function call is unnecessary.  In order for Python to see it as a string, 
>which is necessary for the general case of converting some arbitrary 
>representation, you need to have quotes.
>
>(I'll refrain from commenting on your code, but it looks very

I apologize for the code getting jumbled due to #comments and also  
duplication. This was sloppy
on my part. See attachments if this is not better.

def base(r1,r2,num):            #convert the string num or expression in 
base r1 to base r2
    import math
    num = str(num)
    dec = 0                       #Clear to allow loop input per base
    ln  = len(num)                #save length of string to convert for 
later parsing
    j=0
    while j < ln:                 #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)     #Compute the powers of the radix to 
convert
        ascii2 = decimal(asci)    #Get the decimal value of the ascii code
        dec += ascii2*temp        #Multiply by decimal value and power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the radix to 
convert to
    j = int(PWR)
    while j >= 0:                        #Divide by descending powers of the 
radix to
        Q   = dec/(r2**j)                #get the ascii values
        dec = dec%(r2**j)                #get the remainder of divison for 
next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                  #Concatenate the output string
        j-=1
    print RDX                            #Return the converted r1 to r2 
radix string

def ascii(Q1):
    if   Q1 < 10:                        # 1-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:          # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                    # a-z = ascii 97 - 122
    return Q1

def decimal(Q1):                         # 1 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:         # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                    # a - z = ascii 97 - 122
    return Q1


#****************************calling python from the command line with args 
*************
#base3.py             call convert def base from the msdos console
#                                                     By Cino Hilliard
#Usage:
#c:\python23\python base3.py r1 r2 num.  For example
#c:\Python23>python base3.py 62 10 2Jst0FwPKm
#31415926535897932
#c:\Python23>python base3.py 16 10 FFFF
#65535
# As you can see, the quotes are not required around the value string.
# However, this technique will not allow evaluation as the >>> mode.
# This can be overcome also if anyone wants to know, I will demonstrate.

from math    import *
from sys     import *
from convert import *
r1 = long(argv[1])   #convert the first argument in the command tail to long
r2 = long(argv[2])   #convert the second argument in the command tail to 
long
num =str(argv[3])    #convert the third argument in the command tail to 
string
base(r1,r2,num)

KUDOS
The conversion of my BCX base to base conversion  routine was straight 
forward to python. Only minor
glitches occured which I was able to iron out. Hmmm... no who's on first 
jokes!

This is not the case in my effort to convert to Pari. Major drawback in 
simple string handling is the hold
up. I am having to go through a convolution with Vec(string)

Cheers and Roebuck.

662042196960720285629

_________________________________________________________________
Help STOP SPAM with the new MSN 8 and get 2 months FREE*  
http://join.msn.com/?page=features/junkmail

------=_NextPart_000_42a_6aca_5f1d
Content-Type: text/plain; name="convert.py"; format=flowed
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="convert.py"

#convert.py module    convert.base converts bases 2 to 62 ascii 0-9, A-Z,a-z
#Numbers can be arbitrarily large using python's integer arbitrary 
precision.
#usage:
#>>> import convert to start, reload(convert) while editing.
#>>> convert.base(radix1,radix2,value string in radix1)
#Note value string can be an expression.
#Example
#>>> convert.base(62,10,"2Jst0FwPKm")
#31415926535897932
# we can disect this example to verify the algorithm. First note that a 
number base 62
#can be express as a poloynomial in powers of 62 with coefficients a_i.
#y = a_n*62^n+a_n-1*62^(n-1)+...+a_0*62^0. Then in our example, which is of 
length 10, we
# have a 9th degree base 62 polynomial, y = 2*62^9+J*62^8+s*62^7+...+m*62^0. 
Then when we
#substitute the decimal equivelants of 2Jst0FwPKm into the polynomial, we 
can convert
#this base 62 representation to decimal, y = 
2*62^9+19*62^8+54*62^7+...+48*62^0.
#Evaluating this for 2Jst we have 2*62^9+19*62^8+54*62^7+55*62^6 = 
3.14159263004*10^16.
#So when you see Pi out there in Hex, you will have to determine the power 
of the
#poloynomial before you start using your hex to decimal converter to get the 
familiar
#314159...decimal representation of pi. You can have fun with this converter 
by converting
#text such as phrases or your name etc from base 62 to base 10. For example,
#>>> convert.base(62,10,"PythonIsTheLanguage")
#4761314813537091063939032726114852
#Converting back
#>>> convert.base(10,62,"4761314813537091063939032726114852")
#PythonIsTheLanguage
#convert.base() also allows you to evaluate expressions and then convert 
them.
#For example
#>>> convert.base(10,62,int(math.acos(-1)*10**16))
#2Jst0FwPKm
#You can also allow input at the dos prompt as follows.
def base(r1,r2,num):            #convert the string num or expression in 
base r1 to base r2
    import math
    num = str(num)
    dec = 0                       #Clear to allow loop input per base
    ln  = len(num)                #save length of string to convert for 
later parsing
    j=0
    while j < ln:                 #parse the input string
        asci = ord(num[j])        #Get the ascii code of the char in string 
to convert
        temp   = r1**(ln-j-1)     #Compute the powers of the radix to 
convert
        ascii2 = decimal(asci)    #Get the decimal value of the ascii code
        dec += ascii2*temp        #Multiply by decimal value and power of 
radix
        j+=1
    RDX = ""
    PWR = math.log(dec)/math.log(r2)     #Get max power of r2 the radix to 
convert to
    j = int(PWR)
    while j >= 0:                        #Divide by descending powers of the 
radix to
        Q   = dec/(r2**j)                #get the ascii values
        dec = dec%(r2**j)                #get the remainder of divison for 
next division
        tmp = chr(ascii(Q))
        RDX = RDX + tmp                  #Concatenate the output string
        j-=1
    print RDX                            #Return the converted r1 to r2 
radix string

def ascii(Q1):
    if   Q1 < 10:                        # 1-9 = ascii 48 - 57
         Q1+= 48
    else:
         if Q1 > 9 and Q1 < 36:          # A-Z = ascii 65 - 90
              Q1+= 55
         else:
              Q1+= 61                    # a-z = ascii 97 - 122
    return Q1

def decimal(Q1):                         # 1 - 9 < ascii 58
    if   Q1 < 58:
         Q1-= 48
    else:
         if Q1 > 57 and Q1 < 97:         # A - Z < ascii 97
              Q1-= 55
         else:
              Q1-= 61                    # a - z = ascii 97 - 122
    return Q1


------=_NextPart_000_42a_6aca_5f1d
Content-Type: text/plain; name="base3.py"; format=flowed
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; filename="base3.py"

#base3.py             call convert def base from the msdos console
#                         By Cino Hilliard
#Usage:
#c:\python23\python base3.py r1 r2 num.  For example
#c:\Python23>python base3.py 62 10 2Jst0FwPKm
#31415926535897932
#c:\Python23>python base3.py 16 10 FFFF
#65535
# As you can see, the quotes are not required around the value string.
# However, this technique will not allow evaluation as the >>> mode.
# This can be overcome also if anyone wants to know, I will demonstrate.

from math    import *
from sys     import *
from convert import *
r1 = long(argv[1])   #convert the first argument in the command tail to long
r2 = long(argv[2])   #convert the second argument in the command tail to 
long
num =str(argv[3])    #convert the third argument in the command tail to 
string
base(r1,r2,num)



------=_NextPart_000_42a_6aca_5f1d--