Integer to base-x system using recursion in python

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

    I recommend you structure your code in a more precise way. You can split the vaguely-specified task you mention along different sub-tasks, e.g.:

    • determine and normalize the signs of the number and base (do you need to support negative bases, or can you just raise an exception?), also ensuring an immediate exception gets raised in error cases (e.g. a base of 0 or 1);
    • write a function that (give positive and correct values for a and b) returns a "sequence of digits" to represent a in base b, where a "digit" is an integer between 0 included and b excluded;
    • write a function that given a's sign and sequence-of-digits expansions builds and returns a string representation -- depends on how you want to represent very large "digits" when b is large, say > 36 if you want to use digits, then ASCII letters, for the first 36 digits in the obvious way; maybe you should accept an "alphabet" string to use for the purpose (and the first function above should raise an exception when b's too large for the given alphabet)
    • write a function that uses all the above ones to print the string out

    Of these tasks, only the second one can be seen as suitable to a "recursive" implementation if one insists (though an iterative implementation is in fact much more natural!) -- given that this is homework, I guess you'll have to do it recursively because that's part of the assigned task, ah well!-). But, for reference, one obvious way to iterate would be:

      def digitsequence(a, b):
        results = []
        while True:
          results.append(a % b)
          if a < b: break
          a //= b
        return reversed(results)
    

    assuming one wants the digit sequence in the "big endian" order we're used to from the way positional decimal notation entered Western culture (it was the more naturally-computed little-endian order in the Arabic original... but Arab being written right-to-left, the literal transcription of that order in European languages, written left-to-right, became big-endian!-).

    Anyway, you can take simple, linear recursion as a way to "reverse" things implicitly (you could say such recursion "hides" a last-in, first-out stack, which is clearly a way to reverse a sequence;-), which I guess is where the recursion spec in the homework assignment may be coming from;-).

提交回复
热议问题