Matus
Matus

Reputation: 43

very basic recursion in python

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)

Upvotes: 1

Views: 98

Answers (1)

fafl
fafl

Reputation: 7385

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]

Upvotes: 5

Related Questions