【问题标题】:Python Ternary RescursionPython 三元递归
【发布时间】:2016-10-14 09:41:25
【问题描述】:

我正在创建两个函数,一个返回以 10 为基数的三进制表示,另一个使用递归返回三进制数的以 10 为基数的表示。例如 52 将返回 1221。现在,我已经完成了,但我不知道如何制作它。我对三元表示中的 2 的方面以及如何将其实现到代码中感到困惑。

def numToTernary(n):
 '''Precondition: integer argument is non-negative.
    Returns the string with the ternary representation of non-negative integer
    n. If n is 0, the empty string is returned.'''
    if n==0:
        return ''
    if n<3:
        return str(n)
    return numToTernary(n//3)+

【问题讨论】:

  • 我不确定实际的问题是什么。你也可以在你的代码中检查if n&lt;0,而不是把它作为你的文档字符串的一部分

标签: python recursion ternary


【解决方案1】:

因此,所有基本更改的主要想法如下:

你把number n写成base b当作这个123。这意味着base 10中的n等于1*b² + 2*b + 3。所以从base bbase 10 的转换是直截了当的:你把所有数字乘以正确的幂的底数。

现在进行反向操作:您在base 10 中有一个number n,并希望将其转入base b。该操作只是计算新基数中的每个数字的问题。 (对于以下示例,我假设我的结果只有三位数字)所以我正在寻找 d2,d1,d0 中的数字 base b of n。我知道d2*b² + d1*b + d0 = n。这意味着(d2*b + d1)*b + d0 = n 所以我们认识到欧几里得除法的结果,其中 d0 是 n 除以 d 的欧几里得除法的余数:d0=n%d。我们已将 d0 确定为余数,因此括号中的表达式是 quotien qq=n//b,因此我们有一个新方程可以使用完全相同的方法(因此是递归)d2*b + d1 = q 求解。

所有这些都转化为您几乎拥有的代码:

def numToTernary(n):
    '''Precondition: integer argument is non-negative.
    Returns the string with the ternary representation of non-negative integer
    n. If n is 0, the empty string is returned.'''
    if n==0:
        return ''
    if n<3:
        return str(n)
    return numToTernary(n//3)+str(n%3)

print(numToTernary(10))
Out[1]: '101'

【讨论】:

    【解决方案2】:

    您的代码就快到了。根据this question,这应该可以解决问题。

    但是,您必须在此函数之外搜索“0”:正如您在代码中所做的那样,输出中没有跳过“0”数字,并且应该输出“120011”的数字例如,会改为输出“1211”。

    def numToTernary(n):
        '''Precondition: integer argument is non-negative.
        Returns the string with the ternary representation of non-negative integer
        n. If n is 0, the empty string is returned.'''
        if n<3:
            return str(n)
        return numToTernary(n//3)+str(n%3)
    

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多