Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' finds all possible pairs of integers within defined range that will add up to a target number
- and returns those as a list of tuples. One or more digits can be excluded from the solutions by
- passing one or more integers (int, tuple or int, list of int, None) '''
- def excludes_digits(num, digits=None):
- if not digits:
- return True
- if isinstance(digits, int):
- digits = [digits]
- num_str = str(num)
- for digit in digits:
- if str(digit) in num_str:
- return False
- return True
- def find_sums(arr, target, excluded=None):
- finds = set()
- hash = set()
- if target % 2 == 0: # if target is even need to allow for half + half in arr
- even = target // 2
- if arr.count(even) > 1:
- source = list(set(arr)) + [even] # half in arr twice, need unique numbers but 2 off half
- else:
- source = set(arr) # half not in arr twice so make sure we have unique numbers
- else:
- source = set(arr) # half not in arr so make sure we have unique numbers
- for num in source:
- if excludes_digits(num, excluded):
- candidate = target - num
- if excludes_digits(candidate, excluded) and candidate in hash:
- finds.add((num, candidate))
- hash.add(num)
- return finds
- # example usage
- target = 24 # number to find sums for, i.e. pairs of numbers that add up to target
- exclude = 9, 4 # one or more single digit integers that should be excluded from solutions
- # need to provide a container (list, tuple, set) of numbers that can be used for solutions
- # generated here using a linear range and adding in additional copy of half of target
- # if target is an even number
- lowest = -6 #
- highest = 32 # or maybe use target - lowest
- candidates = list(range(lowest, highest + 1)) + ([target // 2] if target % 2 == 0 else [])
- # look for solutions using numbers referenced by candidates
- finds = find_sums(candidates, target, exclude)
- print(sorted(finds))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement