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
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:
        # 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

+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,160 points
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
• 1,500 points
0 votes
2 answers

what is the procedure to the version of python in my computer?

Execute the following command on your terminal: python ...READ MORE

answered Mar 19 in Python by Alia
+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 130 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
• 12,360 points
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,710 points