Search code examples
pythonpython-3.xlistradix

Convert base to bases within 2 to 9


Okay so I am lost and stuck on how to make any further progress. This program will return the value of the user inputted base into a list like this [1, 2, 2]. I am trying to do two things. First, instead of a single number like

userInt = 50

I want to be able to input

userList = [50, 3, 6, 44]

and then have the formula convert each number to the correct base.

So if I converted this to a base 6, I would want the result to be:

userNewList = [122, 3, 10, 112]

I've tried this with a for loop but can't get it right and end up just throughing an int is not iterable type error.

def baseConversion(userInt, base):
    remList = []
    while(userInt > 0):
        remList.append(userInt % base)
        userInt = userInt // base     
    return (remList[::-1])       


def main():
    base = int(input('Enter a base: '))
    userInt = 50
    remList = baseConversion(userInt, base)
    baseConversion(userInt, base)
    print(remList)
main()

I appreciate any help you can offer.


Solution

  • Using Python 2.7, but you can get the idea:

    >>> def baseConversion(userInt, base):
            remList = ''
            while(userInt > 0):
                remList += str(userInt % base)
                userInt = userInt // base
            return int(remList[::-1]) # If you are just printing, you don't need to convert to int.
    
    >>> def main():
            base = int(raw_input('Enter a base:'))
            userInt = [int(s.strip()) for s in raw_input('Enter numbers (comma separated):').split(',')]
            result = [baseConversion(i, base)  for i in userInt]
            print result
    
    
    >>> main()
    Enter a base:6
    Enter numbers (comma separated):50,3,6,44
    [122, 3, 10, 112]