Integer to base-x system using recursion in python

前端 未结 5 1442
甜味超标
甜味超标 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:10

    You have no return statement in your else block, and you have no recursive call to convert.

    I think you want:

    if a<=1:
        return str(a)
    else:
        return str(convert(a//b,b)) + str(add)
    

    as in

    >>> def convert(a,b):
    ...   add = a%b
    ...   if a<=1:
    ...     return str(a)
    ...   else:
    ...     return str(convert(a//b,b)) + str(add)
    ... 
    >>> convert(10,2)
    '1010'
    

    In general, try to avoid mixing types in recursive functions. It is most often the case that both your base case and your recursive case should return the same type.

提交回复
热议问题