Advertisement
gruntfutuk

sum pairs for num

Jun 28th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. ''' finds all possible pairs of integers within defined range that will add up to a target number
  2. and returns those as a list of tuples. One or more digits can be excluded from the solutions by
  3. passing one or more integers (int, tuple or int, list of int, None) '''
  4.  
  5. def excludes_digits(num, digits=None):
  6.     if not digits:
  7.         return True
  8.     if isinstance(digits, int):
  9.         digits = [digits]
  10.     num_str = str(num)
  11.     for digit in digits:
  12.         if str(digit) in num_str:
  13.             return False
  14.     return True
  15.    
  16. def find_sums(arr, target, excluded=None):
  17.     finds = set()
  18.     hash = set()
  19.     if target % 2 == 0:  # if target is even need to allow for half + half in arr
  20.         even = target // 2
  21.         if arr.count(even) > 1:
  22.             source = list(set(arr)) + [even]  # half in arr twice, need unique numbers but 2 off half
  23.         else:
  24.             source = set(arr)  # half not in arr twice so make sure we have unique numbers
  25.     else:
  26.         source = set(arr)  # half not in arr so make sure we have unique numbers
  27.     for num in source:
  28.         if excludes_digits(num, excluded):
  29.             candidate = target - num
  30.             if excludes_digits(candidate, excluded) and candidate in hash:
  31.                 finds.add((num, candidate))
  32.             hash.add(num)        
  33.     return finds
  34.  
  35. # example usage
  36. target = 24  # number to find sums for, i.e. pairs of numbers that add up to target
  37. exclude = 9, 4  # one or more single digit integers that should be excluded from solutions
  38.  
  39. # need to provide a container (list, tuple, set) of numbers that can be used for solutions
  40. # generated here using a linear range and adding in additional copy of half of target
  41. # if target is an even number
  42. lowest = -6 #
  43. highest = 32 # or maybe use target - lowest
  44. candidates = list(range(lowest, highest + 1)) + ([target // 2] if target % 2 == 0 else [])
  45.  
  46. # look for solutions using numbers referenced by candidates
  47. finds = find_sums(candidates, target, exclude)
  48. print(sorted(finds))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement