1
I am needing to run the following function below on AWS Lambda:
def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print("sum(%s)=%s" % (partial, target))
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i + 1:]
subset_sum(remaining, target, partial + [n])
if __name__ == "__main__":
subset_sum([1,2,3], 5)
Yet this one comes along and I can’t fix it:
{
"errorMessage": "'>=' not supported between instances of 'int' and 'LambdaContext'",
"errorType": "TypeError",
"stackTrace": [
[
"/var/task/lambda_function.py",
7,
"subset_sum",
"if s >= target:"
]
]
}
The original function has more values that take a long time so I’m trying to run on Lambda. The function returns the combination of numbers that result in the sum of the defined value (in case 5)
On the computer using py subset_sum.py
works normally and returns 2 and 3 (which combined is equal to 5).
UPDATING
I made the modification as Tom replies. Now reports another error.
def lambda_handler(event, context):
s = sum(event['partial'])
if s == 5:
print("sum(%s)=%s" % (event['partial'], 5))
exit()
if s >= 5:
return
for i in range(len(event['numbers'])):
n = event['numbers'][i]
remaining = event['numbers'][i + 1:]
dict = {'numbers' : remaining, 'partial' : event['partial'] + [n]}
lambda_handler(dict)
if __name__ == "__main__":
dict = {'numbers' : [1,2,3], 'partial' : []}
lambda_handler(dict)
Output from the Lambda
{
"errorMessage": "'partial'",
"errorType": "KeyError",
"stackTrace": [
[
"/var/task/lambda_function.py",
5,
"lambda_handler",
"s = sum(event['partial'])"
]
]
}
Print(Event) output at the very beginning of Handler
START RequestId: f3a45f36-b1fc-11e7-8f6d-d5a3a428a4fd Version: $LATEST
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
'partial': KeyError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 7, in lambda_handler
s = sum(event['partial'])
KeyError: 'partial'
END RequestId: f3a45f36-b1fc-11e7-8f6d-d5a3a428a4fd
Tip: There are tools that simulate a lambda environment on your machine (eg serveless framework), use them to test your code locally and after testing deploy the code on lambda, this helps a lot to find errors before they go to Amazon (I’ve suffered enough with this).
– JanMic