10.4k views
5 votes
Design and implement an algorithm that gets as input a list of k integer values N1, N2,..., Nk as well as a special value SUM. Your algorithm must locate a pair of values in the list N that sum to the value SUM. For example, if your list of values is 3, 8, 13, 2, 17, 18, 10, and the value of SUM is 20, then your algorithm would output either of the two values (2, 18) or (3, 17). If your algorithm cannot find any pair of values that sum to the value SUM, then it should print the message ‘Sorry, there is no such pair of values’. Schneider, G.Michael. Invitation to Computer Science (p. 88). Course Technology. Kindle Edition.

User JeffHeaton
by
8.0k points

1 Answer

7 votes

Answer:

Follows are the code to this question:

def FindPair(Values,SUM):#defining a method FindPair

found=False;#defining a boolean variable found

for i in Values:#defining loop for check Value

for j in Values:#defining loop for check Value

if (i+j ==SUM):#defining if block that check i+j=sum

found=True;#assign value True in boolean variable

x=i;#defining a variable x that holds i value

y=j;#defining a variable x that holds j value

break;#use break keyword

if(found==True):#defining if block that checks found equal to True

print("(",x,",",y,")");#print value

else:#defining else block

print("Sorry there is no such pair of values.");#print message

Values=[3,8,13,2,17,18,10];#defining a list and assign Values

SUM=20;#defining SUM variable

FindPair(Values,SUM);#calling a method FindPair

Output:

please find the attachment:

Step-by-step explanation:

In the above python code a method, "FindPair" is defined, which accepts a "list and SUM" variable in its parameter, inside the method "found" a boolean variable is defined, that holds a value "false".

  • Inside the method, two for loop is defined, that holds list element value, and in if block, it checks its added value is equal to the SUM. If the condition is true, it changes the boolean variable value and defines the "x,y" variable, that holds its value.
  • In the next if the block, it checks the boolean variable value, if the condition is true, it will print the "x,y" value, otherwise, it will print a message.
Design and implement an algorithm that gets as input a list of k integer values N-example-1
User Fervus
by
7.7k points