【问题标题】:Function to convert a decimal into that of any base将小数转换为任何基数的函数
【发布时间】:2017-07-31 16:03:07
【问题描述】:

我正在通过在线学习平台做这个问题,并且分配了我必须通过的测试用例。 主题是高阶函数。

问题来了:

编写一个函数 make_decimal_to_n_ary_converter,它接受一个数字 n,其中 1

下面是我的代码(我应该使用内部函数,即转换器(x))

    def make_decimal_to_n_ary_converter(n):
    def converter(x):
        if x==0 or x==1:   
            return x
        i=x
        b=('A','B','C','D','E','F')
        result = ""
        while i>0:
            a=i%n          #3
            if a<10:
                result = str(i%n)+result
            else:
                d=a-10
                result = b[d] + result
            i=i//n

        return result
    return converter

#Lines below are not to be changed, part of qn
decimal_to_binary = make_decimal_to_n_ary_converter(2)
decimal_to_octal = make_decimal_to_n_ary_converter(8)
decimal_to_hexadecimal = make_decimal_to_n_ary_converter(16)

以下是我的代码通过的一些测试用例:

decimal_to_binary(213)
11010101
十进制转八进制(213)
325
decimal_to_hexadecimal(213)
D5
make_decimal_to_n_ary_converter(15)(213)
E3

但是,我的代码未能通过一些私人测试用例,我收到的反馈是我在 while 循环中的逻辑是错误的。但是,在打印了一些数字后,我没有发现任何错误。 非常感谢您的帮助,谢谢!

【问题讨论】:

    标签: binary hex converter higher-order-functions


    【解决方案1】:

    解决了。我的错误是对于基本情况 x ,我不得不返回一个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多