After Formatting Python Code, Errors Arise
I wrote a python code, which works correctly with no errors: def subset_sum(numbers, target, partial=[]): global max s = sum(partial) # check if the partial sum is
Solution 1:
First of all, a note: don't use max
as a variable name; it is a built-in function which returns the item in a list with the highest value.
In your subset_sum()
function, you have the line
str1 = ''.join(str(e) for e in max)
Which tries to iterate (loop) through the predefined function, as there is no redefinition of max
before you use it (variables need to be created/defined/initalised before you use them).
Sure, you do have global max
at the beginning of the function, but because there is no variables called max
outside of the function, it defaults to using the built-in function.
Fixed code (note the usage of _max
rather than maximum
):
def subset_sum(numbers, target, partial=[]):
global _max
s = sum(partial)
# check if the partial sum is equals to target
if s%3 == 0:
# print "sum(%s)=%s" % (partial, target)
if s != 0:
str1 = ''.join(str(e) for e in partial)
y = int(str1)
str1 = ''.join(str(e) for e in _max)
z = int(str1)
if y>z:
_max = partial
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])
def answer(l):
global _max
subset_sum(l,15)
_max = sorted(_max, key=int, reverse=True)
return _max
_max = [0, 0, 0, 0,0];
answer([3,1,4,1,5,9])
Post a Comment for "After Formatting Python Code, Errors Arise"