Advertisement
igendel

Partition Problem Solver

Aug 29th, 2022 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. # Partition Problem Solver
  2. # by Ido Gendel, 2022
  3. # Share and enjoy... at your own risk!
  4.  
  5. import sys
  6. import random
  7.  
  8. def findSum(data, index, target):
  9.  
  10.     if data[index] > target:
  11.         return False
  12.     elif data[index] == target:
  13.         print("Index =", index, ", Value =", data[index])
  14.         return True
  15.  
  16.     subTarget = target - data[index]
  17.     subScanIndex = index - 1
  18.  
  19.     # Scan through the remaining values
  20.     while subScanIndex >= 0:
  21.         if findSum(data, subScanIndex, subTarget):
  22.             print("Index =", index, ", Value =", data[index])
  23.             return True
  24.         subScanIndex -= 1        
  25.  
  26.     return False
  27.        
  28.        
  29. # Create an array with random positive integers
  30. testData = []
  31. for n in range(random.randint(1, 40)):
  32.     testData.append(random.randint(1, 50))
  33.  
  34. print("Original array:", testData)
  35.  
  36. if 2 > len(testData):
  37.     print("Array too small - no solution")
  38.     sys.exit()
  39.    
  40. dataSum = sum(testData)
  41. if 1 == (dataSum % 2):
  42.     print("Odd sum", dataSum, "- no solution")
  43.     sys.exit()
  44.  
  45. halfSum = dataSum // 2
  46. testData.sort()
  47. print("Sorted array:", testData)
  48. print("Sum =", dataSum, ", Looking for a subset with the sum", halfSum, "...")
  49. if (not findSum(testData, len(testData) - 1, halfSum)):
  50.     print("No solution found")
  51. else:
  52.     print("Done!")
  53.    
  54. # Example for even sum but no solution: [14, 31, 29, 17, 22, 17, 12, 21, 17]
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement