1

I have this problem that I can't really solve, I guess it is because I don't really understand recursion...but I have this function that I need to implement.

def elements(num, multiplier, add, limiter) -> List[int]:

num is a number which you multiply by the multiplier and then add the number add...and you will append the number num untill it is larger than limiter.

for example

(5, 3, 1, 20) will give [5, 16] 
(5, 3, 1, 5) will give []
(4, -2, -2, 74) will give [4, -10, 18, -38]

I can not use any cycles so no for cycle or while cycle...or anything that contains cycle in it(sum, min, max....and so on)

I wrote this, and I know it is stupid, but I don't really understand how recursion works I guess...that is why I came here because I learn best from code

def first_elements(first, multiplier, addend, limit):
    result = []
    if first > limit:
        return []
    multiplied,_,_,_ = first_elements(first * multiplier + addend, multiplier, addend, limit)
    if multiplied > limit:
        return []
    result.append(first)
    result.append(multiplied)
3
  • What do you mean by append the number add until its is larger than the limiter ? Commented Jan 24, 2020 at 13:22
  • You never have to use recursion if you don't want too. Every solution that uses recursion can be written in an iteration as well. :) Commented Jan 24, 2020 at 13:25
  • I meant that number can be appended if it is lower than limiter. Sorry if it was written badly. I had to use recursion to solve this :D Commented Jan 24, 2020 at 13:33

1 Answer 1

5

Something like this?

def solve(first, multiplier, addend, limit):
    if limit <= first:
        return []
    return [first] + solve(first * multiplier + addend, multiplier, addend, limit)

print(solve(4, -2, -2, 74))  # prints [4, -10, 18, -38]
Sign up to request clarification or add additional context in comments.

3 Comments

Its a homework question no? I don't know if we are supposed to answer them like this.....
@JasonChia Well, the OP clearly showed a solution, so why not help? It was no dump of a homework question.
I guess...but it kinda defeats the purpose of understanding how recursive functions work. Perahaps @fafl can explain what went wrong with the Op's code. it was really close.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.