简体   繁体   中英

Higher Order Function Python (never ending?)

I have a code that works when it's input with an increasing value like '123' but not when the next character is smaller than the previous character (eg. '132') and if there's a same number, the recursion never stops (eg. '122')

Please kindly point out the issue in my code and a solution would be appreciated greatly.

def sum(term, a, next, b):
    if (a > b):
        return 0
    else:
        print (term(a), a, next(a), b)
        return term(a) + sum(term, next(a), next, b)

def knocked_down(game):

    t1 = lambda x:int(game[x])
    t2 = 0
    t3 = lambda x: int(game[x])
    t4 = len(game)-1
    return sum(t1, t2, t3, t4)

results=knocked_down("123")
print('---')
print(results)

In sum function, the parameters might mean

  • term : Function to get value by index
  • a : Start index
  • next : Function to get next index
  • b : Last index

And OP said:

The sum() function wasn't written by me. I was tasked to use it and I'm not allowed to change the code.

So I didn't touch sum function.
You can change t3 into lambda x: x + 1 .

def sum(term, a, next, b):
    if (a > b):
        return 0
    else:
        print(term(a), a, next(a), b)
        return term(a) + sum(term, next(a), next, b)


def knocked_down(game):
    t1 = lambda x: int(game[x])
    t2 = 0
    t3 = lambda x: x + 1
    t4 = len(game) - 1
    return sum(t1, t2, t3, t4)


results = knocked_down("132")
print('---')
print(results)

output:

1 0 1 2
3 1 2 2
2 2 3 2
---
6

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