简体   繁体   English

Python递归函数

[英]Python recursion function

I am trying to take a number, do floor division on it, until it becomes 0. This must be done using recursion with a base case. 我正在尝试取一个数字,对其进行地板除法,直到变为0。这必须使用带有基本情况的递归来完成。 For example: 例如:

>>>Base(5,2)
2 ##(5//2)
1 ##(2//2)
0 ##(1//2)

This is what I have so far: 这是我到目前为止的内容:

def Base(number,base):
    result=1
    if result==0:
        return False
    else:
        result=number//base
        return Base(result,base)

I think this is what you are looking for 我想这就是你要找的

def Base(number,base):

        if number==0:
            return False
        else:
            number = number//base
            print(number)
            return Base(number,base)

First of all using result = 1 should be removed as during every recursive call result will be reinitialized to 1 and the following if statement will never work. 首先,应删除using result = 1,因为在每次递归调用期间,结果都将被初始化为1,并且随后的if语句将永远无法工作。 What you needed to do was to keep on dividing the number recursively till it reaches 0 and print False 您需要做的是继续递归除数,直到达到0并打印False

I hope it clears your doubt 我希望它清除您的疑问

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

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