Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5622355

Browse files
committed
Determine two elements from the array whose sum is equal to specified sum
1 parent9122c79 commit5622355

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎Arrays/P05_CheckForPairSum.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Author: OMKAR PATHAK
2+
3+
# Given an array A[] of n numbers and another number x, determines whether or not there exist two elements
4+
# in S whose sum is exactly x.
5+
6+
defcheckSum(array,sum):
7+
# sort the array in descending order
8+
array=quickSort(array)
9+
10+
leftIndex=0
11+
rightIndex=len(array)-1
12+
13+
whileleftIndex<rightIndex:
14+
if (array[leftIndex]+array[rightIndex]==sum):
15+
returnarray[leftIndex],array[rightIndex]
16+
elif(array[leftIndex]+array[rightIndex]<sum):
17+
leftIndex+=1
18+
else:
19+
rightIndex+=1
20+
21+
returnFalse,False
22+
23+
defquickSort(array):
24+
iflen(array)<=1:
25+
returnarray
26+
pivot=array[len(array)//2]
27+
left= [xforxinarrayifx<pivot]
28+
middle= [xforxinarrayifx==pivot]
29+
right= [xforxinarrayifx>pivot]
30+
returnquickSort(left)+middle+quickSort(right)
31+
32+
if__name__=='__main__':
33+
myArray= [10,20,30,40,50]
34+
sum=80
35+
36+
number1,number2=checkSum(myArray,sum)
37+
if(number1andnumber2):
38+
print('Array has elements:',number1,'and',number2,'with sum:',sum)
39+
else:
40+
print('Array doesn\'t has elements with the sum:',sum)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp