I have the following code in JavaScript to compute the minimum elements in array whose sum equals n
:
function findMinSum(arr, n){
if(!arr) return
let min
for (let i=0; i<arr.length; i++) {
/* if a number equals the sum, it's obviously
* the shortest set, just return it
*/
if (arr[i] == n) return [arr[i]]
/* recursively call on subset with
* sum adjusted for removed element
*/
let next = findMinSum(arr.slice(i+1), n-arr[i])
/* we only care about next if it's shorter then
* the shortest thing we've seen so far
*/
if (next){
if(min === undefined || next.length < min.length){
min = [arr[i], ...next]
}
}
}
return min && min /* if we found a match return it, otherwise return undefined */
}
I got this code from here.
I wanted to convert it to Python, so I did the following:
def findMinSum(arr, n):
if not arr:
return
min = []
min_len = len(min)
for i in range(0, len(arr)):
if(arr[i] == n):
return (arr[i])
next = []
next = findMinSum(arr[i+1:], n-arr[i])
if(next == list):
next_len = len(next)
else:
next_len = next
if(next):
print(next) # printing next for debugging purpose
if( ( not min ) or (next_len < min_len) ):
min = [ next, arr[i]]
return min
arr = [8, 6, 1, 5, 9, 3]
get_min = findMinSum(arr, 14)
print(get_min)
But when I run this code, I get the following error:
3
[3, 1]
9
[[3, 1], 6]
3
[3, 9]
Traceback (most recent call last):
File "test1.py", line 34, in <module>
min2 = findMinSum(arr, 14)
File "test1.py", line 25, in findMinSum
if( ( not min ) or (next_len < min_len) ):
TypeError: '<' not supported between instances of 'list' and 'int'
The expected output should be [8, 6]
or [9, 5]
.
I can't think of any other way to write the code as I'm a newbie to Python. Also I don't want to import any other module except numpy.
Where did I go wrong with this translation?