简体   繁体   中英

Why is my recursive function won't work and why do I get strange results

I need to write a code that will take a string of numbers and find consecutive 5 digits that will give me the highest possible number (as in 9328498503734 the answer will be 9850374).

x = 0    
def solution(digits):
    global x 
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        solution(digits[1:])

My idea was to do it with recursive function - check if the length of the input is not less than 5, if not, then check if the current 5 digits are the biggest number. If so, this number becomes new x, and function gets repeated but without the first digit until the base case is missed.

So my first problem is how to do this without a global variable? I heard they are shunned but when I was writing previous recursive code and used any variable inside that function it got reset every time.

My next problem is that this function returns None and I have no idea why? Also, when I tried to put "print (len(digit))" over global x for each recursion, I can see what's going on! Instead of returning 'None' it raises "RuntimeError: maximum recursion depth exceeded while calling a Python object" and I have no idea why? Although, without this counter, I have None as a return.

So, how to do it without a global variable and why does my code change it's behavior so much over a simple print statement?
Your help would be appreciated!

EDIT: Ok, I was getting None, because I tried to call function from inside function, but I forgot that it has to be called with "return", not just like that, like I would do it outside a function.

Big thank you to the user below who told me that I can carry ariable in a function by placing this variable in function parenthesis. I would definitely not recommend Codecademy, as it omits such simple and important thing, giving only very basic and incomplete knowledge of the topic. I finished their Python course, all exercises and this is how much I know after this:/

Instead of using a global variable, pass x 'along' when you call the function. By setting it to have a default value of 0 it doesn't need to be passed in at the start:

def solution(digits, x=0):
    if len(digits) < 5:
        return x
    else:
        if int(digits[0:5]) > x:
            x = int(digits[0:5])
        return solution(digits[1:], x)

print(solution('9328498503734'))
98503

Typically to make a recursive function work, you need to return some kind of combination of a base result with the result of another recursive call on a reduced version of the original argument. Using globals is usually going to be self-defeating because all the recursive calls will overwrite each other (there's a reason using globals is "shunned", it's because it usually makes your code not work , lol).

>>> def solution(digits: str) -> str:
...     """Returns the 5-digit substring of digits with the highest int value."""
...     if len(digits) <= 5:
...         return digits
...     else:
...         return max(digits[:5], solution(digits[1:]), key=int)
...
>>> solution("9328498503734")
'98503'
def max_5_digits(digits, _max=0):
    return _max if len(digits) < 5 else max_5_digits(digits[1:], max(_max, int(digits[:5])))
max_5_digits("9328498503734")                                                                                                                                                                           
## 98503

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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