import sys def subsetSum(nums, total): n = len(nums) T = [[False for x in range(total + 1)] for y in range(n + 1)] for i in range(n + 1): T[i][0] = True for i in range(1, n + 1): for j in range(1, total + 1): if nums[i - 1] > j: T[i][j] = T[i - 1][j] else: T[i][j] = T[i - 1][j] or T[i - 1][j - nums[i - 1]] return T[n][total] def partition(nums): total = sum(nums) return total & 1 == 0 and subsetSum(nums, total // 2) def backtrack(nums, i, p, q): if i == len(nums): if sum(p) == sum(q): print(f"List: {nums}") print("The two sublists with equal sum are: ") print(p) print(q) sys.exit() return p.append(nums[i]) backtrack(nums, i + 1, p, q) p.pop() q.append(nums[i]) backtrack(nums, i + 1, p, q) q.pop() if __name__ == '__main__': nums = [7, 3, 1, 5, 4, 8] if partition(nums): backtrack(nums, 0, [], []) else: print('Set cannot be partitioned') How can I edit my code such that it can handle float input? The image shows the error I have encountered. Thanks in advanced!
import sys
def subsetSum(nums, total):
n = len(nums)
T = [[False for x in range(total + 1)] for y in range(n + 1)]
for i in range(n + 1):
T[i][0] = True
for i in range(1, n + 1):
for j in range(1, total + 1):
if nums[i - 1] > j:
T[i][j] = T[i - 1][j]
else:
T[i][j] = T[i - 1][j] or T[i - 1][j - nums[i - 1]]
return T[n][total]
def partition(nums):
total = sum(nums)
return total & 1 == 0 and subsetSum(nums, total // 2)
def backtrack(nums, i, p, q):
if i == len(nums):
if sum(p) == sum(q):
print(f"List: {nums}")
print("The two sublists with equal sum are: ")
print(p)
print(q)
sys.exit()
return
p.append(nums[i])
backtrack(nums, i + 1, p, q)
p.pop()
q.append(nums[i])
backtrack(nums, i + 1, p, q)
q.pop()
if __name__ == '__main__':
nums = [7, 3, 1, 5, 4, 8]
if partition(nums):
backtrack(nums, 0, [], [])
else:
print('Set cannot be partitioned')
How can I edit my code such that it can handle float input? The image shows the error I have encountered. Thanks in advanced!
Step by step
Solved in 2 steps