Check if there exists two elements in the array whose sum is equal to the sum of the entire array

0 votes
I've recently started learning python and I have an assignment which I need help with.

Write python code to check if there exist two elements in the array whose sum is equal to the sum of the entire array
Jun 17 in Python by Harsh
86 views
Hahah! Its an assignment and you should do it by yourself. I can help with working around the logic.
Hahah! Help me out with the logic. That'd be good enough.

2 answers to this question.

0 votes
You can find the sun of the array. Then for each element in the array a[i], look for a value that is equal to sum - a[i].
answered Jun 17 by Viky
0 votes

You can try something like this Harsh:

def checkPair(a, n):
    s = set()
    sum = 0
    # Find sum of whole array
    for i in range(n):
        sum += a[i]
    # / If sum of array is not
    # even than we can not
    # divide it into two part
    if sum % 2 != 0:
        return False
    sum = sum / 2
    # For each element arr[i], see if
    # there is another element with
    # value sum - arr[i]
    for i in range(n):
        val = sum - a[i]
        if a[i] not in s:
            s.add(a[i])
        # If element exist than
        # return the pair
        if val in s:
            print("Pair elements are",
                  a[i], "and", int(val))
        # Driver Code
a = [2, 11, 5, 1, 4, 7]
n = len(a)
if checkPair(a, n) == False:
    print("No pair found")
answered Jun 17 by Ayman

Related Questions In Python

0 votes
0 answers

What is the logic to check if a number is prime or not in python?

I am looking for a function with ...READ MORE

Aug 2 in Python by Waseem
• 4,470 points
24 views
+1 vote
1 answer

How to check if a string is null in python

Try this: if cookie and not cookie.isspace(): # the ...READ MORE

answered Aug 20, 2018 in Python by Priyaj
• 56,940 points
4,321 views
0 votes
1 answer

how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

answered Mar 12 in Python by Mohammad
• 3,060 points
59 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 349 views
+4 votes
6 answers
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,190 points
76 views
0 votes
1 answer

Is there a foreach function in python and is there a way to implement it if there isnt any

Every occurence of "foreach" I've seen (PHP, ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
89 views