Skip to content
Advertisement

Recursion ( kind of sub-set sum, but not exactly ) – True if can buy pens at exact price, else False

I have this question: you have a list of [7,9,11] pens. you have a function:

JavaScript

you need to check whether or not if you can buy the exact amount.
for example, I have X=23
I can buy 1*9, 2*7
I just need to return True if it is able, false else.
I saw the answer, they did it brute force with 3 for loops ( crazy ).
I tried recursion, it is good, but seems like it is long + duplicated parts + its not exactly good, cus I don’t know where to put the False statement.. what is my exit point.
The code works, but not exactly.

JavaScript

How to fix it? also, what is my thought on the exit statement here? I dont know how to exit it… Where should I put false, and how?

Edit: added prints + outputs

JavaScript

output:

JavaScript

I should receive at none – False. but I dont know where to put the False statement… when all the recursion end, I dont know how to put it.

Advertisement

Answer

The recursive call should be made with each price subtracted from x, until x is either 0 (in which case return True) or less than 0 (in which case return False):

JavaScript

If you just want your code fixed, you can return False at the end of the function when all conditions that would return True fall through:

JavaScript

Or if you are allowed to make a for loop:

JavaScript

Demo: https://replit.com/@blhsing/MortifiedImmediateCheckpoint

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement