简体   繁体   English

将递归结果转换为字符串,以便向后打印

[英]Convert a recursion result to string in order to print it backwards

Here is my code so far: 到目前为止,这是我的代码:

import string  
def convert(num,base):
    if num==0:
        return 
    else:
        remainder = num%base
        num = num//base
        b=(str(remainder))
        print(b[::-1],end="")
        return convert(num,base)

Instead of printing this: 而不是打印此:

>>> convert(29,3)
2001

I need to print it backward like this (and it needs to be done by strings): 我需要像这样向后打印(它需要通过字符串完成):

>>> convert(29,3)
1002

Seems like string does not work well with recursion: 似乎字符串不适用于递归:

>>> convert(29,3)
 ('2', ('0', ('0', ('1', None))))

Just change the order in which you print and recurse: 只需更改打印和递归的顺序即可:

import string  
def convert(num,base):
    if num==0:
        return 
    remainder = num % base
    num = num // base
    convert(num, base)
    print(remainder, end="")

>>> convert(29,3)
1002

No idea what convertBase() is. 不知道什么是convertBase()

Throwing in my $0.02. 投入我的$ 0.02。 I would opt for returning the entire string, instead of printing it as you go. 我会选择返回整个字符串,而不是随便打印它。

def convert(num, base):
    if num == 0:
        return ''
    num, remainder = divmod(num, base)
    return convert(num, base) + str(remainder)

EDIT might as well use the built-in divmod for computing the num and remainder. EDIT也可以使用内置的divmod来计算num和剩余数。

Your recursive function is correct in the sense that it has a exit clause ( if num == 0: ), however due to the nature of recursive functions the order of execution will be the reverse of what you wish to print out. 您的递归函数具有退出子句( if num == 0: ,这是正确的,但是由于递归函数的性质,执行顺序将与您希望打印的顺序相反。 What needs to be done here is to keep adding the remainders to a list and then finally when you hit the exit clause, reverse that list and print it. 这里需要做的是继续将余数添加到列表中,然后最后在单击exit子句时,反转该列表并打印出来。

import string  
def convert(num, base, rem_list=None):
    if not rem_list:
        rem_list = []
    if num == 0:
        rem_list.reverse()
        print "".join(rem_list) 
    else:
        remainder = num % base
        num = num // base
        rem_list.append(str(remainder))
        return convert(num, base, rem_list)



>>> convert(29, 3)
1002
>>> convert(29, 3)
1002

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM