TAGS :Viewed: 18 - Published at: a few seconds ago

[ A python code to convert a number from any base to the base of 10 giving errors . What is wrong with this code? ]

import math 




def baseencode(number, base):
    ##Converting a number of any base to base10

    if number == 0:
        return '0'

    for i in range(0,len(number)):
        if number[i]!= [A-Z]:
            num = num + number[i]*pow(i,base)
        else :
            num = num + (9 + ord(number[i])) *pow(i,base)
    return num

a = baseencode('20',5)
print a 

Errors I get are

Traceback (most recent call last):
  File "doubtrob.py", line 19, in <module>
    a = baseencode('20',5)
  File "doubtrob.py", line 13, in baseencode
    if number[i]!= [A-Z]:
NameError: global name 'A' is not defined

Answer 1


Isn't int(x, base) what you need?

int('20',5) # returns the integer 10

Answer 2


You're confusing Python with... Perl or something...

if not ('A' <= number[i] <= 'Z'):

Answer 3


A more comprehensive solution to this problem may look like this:

import string

# Possible digits from the lowest to the highest
DIGITS = '%s%s' % (string.digits, string.lowercase)

def baseencode(num, base):
    result = 0
    positive = True
    # If a number is negative let's remove the minus sign
    if num[0] == '-':
        positive = False
        num = num[1:]

    for i, n in enumerate(num[::-1]):
        # Since 0xff == 0xFF
        n = n.lower()
        result += DIGITS.index(n) * base ** i

    if not positive:
        result = -1 * result

    return result

Basically whilst converting a number to base 10 it's easiest to start from the last digit, multiply it by the base raised to the current position (DIGITS.index(n) * base ** i).

BTW, in my understanding it's a Python exercise, but if it's not there's a builtin function for that - int:

int(x[, base]) -> integer

Answer 4


There are many errors in your code. To begin with,

number[i] != [A-Z]

is not Python syntax at all. What you probably want is

number[i].isdigit()

Furthermore, the

if number == 0:
    return '0'

part should probably be

if number == '0':
    return 0

but actually, there is no need to special-case this at all. Another problem is that you interpreting the first character as "ones", i.e. lowest significant. There are a few more problems, but maybe this will get you going...

That said, you could simply use

int('20',5)

Answer 5


Other bugs in the code:
1. You didn't initialize variable num that you used to store results.
2. you need to convert number[i] from char to int before you can apply multiplication/addition.

    num = num + int(number[i]) * pow(i,base)

Answer 6


You probably want

if number[i] not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":

or

import string
# ...
if number[i] not in string.ascii_uppercase:

Answer 7


import math

def base_encode(number, base):
    """Convert number in given base to equivalent in base10

    @param number: string, value to convert (case-insensitive)
    @param base:   integer, numeric base of strNumber

    @retval: integer, x base(10) == number base(base)
    """
    # sanitize inputs
    number = str(number).lower()
    base = int(base)

    # legal characters
    known_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
    value  = { ch:val for val,ch in enumerate(known_digits) if val<base }

    # handle negative values    
    if number[0]=='-':
        sign = -1
        number = number[1:]
    else:
        sign = 1

    # do conversion
    total = 0
    for d in number:
        try:
            total = total*base + value[d]
        except KeyError:
            if d in known_digits:
                raise ValueError("invalid digit '{0}' in base {1}".format(d, base))
            else:
                raise ValueError("value of digit {0} is unknown".format(d))

    return sign*total

base_encode('20', 5)     ->  10
base_encode('-zzz', 36)  -> -46655