Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- for i, item in enumerate(numbers):
- for j in range(i+1, len(numbers)):
- total_of_two_items = numbers[i] + numbers[j]
- if(total_of_two_items == total_number):
- print '{first_item} {second_item}'.format(first_item=i+1, second_item=j+1)
- print 'n'
- n = 181
- n2 = n//2
- numbers = [80, 98, 83, 92, 1, 38, 37, 54, 58, 89]
- goodnums = {n-x for x in numbers if x<=n2} & {x for x in numbers if x>n2}
- pairs = {(n-x, x) for x in goodnums}
- if not n%2 and (n2, n2) in pairs and numbers.count(n2) == 1:
- pairs.remove((n2, n2))
- def mergeSort(A):
- if len(A) > 1:
- mid = len(A)//2
- lefthalf = A[:mid]
- righthalf = A[mid:]
- mergeSort(lefthalf)
- mergeSort(righthalf)
- # Merge the halves
- i,j,k=0,0,0
- while i<len(lefthalf) and j<len(righthalf):
- if lefthalf[i] < righthalf[j]:
- A[k] = lefthalf[i]
- i = i + 1
- else:
- A[k] = righthalf[j]
- j = j + 1
- k = k + 1
- while i < len(lefthalf):
- A[k] = lefthalf[i]
- k = k +1
- i = i + 1
- while j < len(righthalf):
- A[k] = righthalf[j]
- k = k + 1
- j = j + 1
- def find_pairs(alist, item):
- # We take two flags left and right to point to the ends of the sorted list
- left = 0
- right = len(alist) - 1
- pairs = []
- while(left<right):
- # We find the sum of the numbers in at these two points.
- # If the sum is equal to our number for which we are finding pairs, we consider this pair and add it to our results
- # If the sum is greater than expected then we move the right pointer one step back to a smaller number and then compute sum again
- # If the sum is smaller than expected then we move the left pointer a step ahead and check the sum with a greater number
- sum = alist[left] + alist[right]
- if sum == item:
- pairs += [(alist[left],alist[right])]
- # Move the pointers to next elements in the list and find more pairs
- right -= 1
- left += 1
- elif sum > item:
- right -= 1
- else:
- left += 1
- return pairs
- l1 = [80, 98, 83, 92, 1, 38, 37, 54, 58, 89]
- mergeSort(l1)
- print l1
- print find_pairs(l1,181)
- l2 = [-5,-2, -23, 34,21,90,1,0,65,8,-10]
- mergeSort(l2)
- print l2
- print find_pairs(l2,-2)
- [1, 37, 38, 54, 58, 80, 83, 89, 92, 98]
- [(83, 98), (89, 92)]
- [-23, -10, -5, -2, 0, 1, 8, 21, 34, 65, 90]
- [(-23, 21), (-10, 8), (-2, 0)]
- def sum_of_pairs_matches(K, arr):
- uniques = {i: True for i in arr}
- pairs = set()
- for val in arr:
- k = -val + K if val<K else -K - val
- if(uniques.get(k, False)):
- pairs.add(tuple(sorted([k,val])))
- return pairs
- sum_of_pairs_matches(5, [-5, -4, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
- {(-5, 10), (-4, 9), (-1, 6), (0, 5), (1, 4), (2, 3)}
Add Comment
Please, Sign In to add comment