Integer to base-x system using recursion in python

前端 未结 5 1500
甜味超标
甜味超标 2021-01-25 01:21

I am trying to write a recursive code that can convert a number to any base system. for example, the integer 10 into binary would convert to 1010

So far I have this but

5条回答
  •  心在旅途
    2021-01-25 02:18

    A simple recursive solution (with limitations) and code to test it:

    from string import hexdigits
    
    def convert(a, b):
    
        return '0' if a == 0 else convert(a // b, b).lstrip('0') + hexdigits[a % b]
    
    if __name__ == '__main__':
    
        # Test code
    
        from random import randint
    
        for _ in range(10):
            number = randint(0, 1000)
            base = randint(2, 16)
    
            conversion = convert(number, base)
    
            print(number, "base", base, "->", conversion, "->", int(conversion, base), "base", base)
    

    Limitations include lack of support for negative numbers; currently limited to bases in the range 2 - 16; doesn't test for invalid arguments.

    TEST RUN

    % python3 test.py
    127 base 3 -> 11201 -> 127 base 3
    666 base 3 -> 220200 -> 666 base 3
    348 base 2 -> 101011100 -> 348 base 2
    139 base 10 -> 139 -> 139 base 10
    464 base 7 -> 1232 -> 464 base 7
    330 base 11 -> 280 -> 330 base 11
    633 base 10 -> 633 -> 633 base 10
    789 base 4 -> 30111 -> 789 base 4
    355 base 15 -> 18a -> 355 base 15
    582 base 8 -> 1106 -> 582 base 8
    %
    

提交回复
热议问题