Need a python script that can run the following, thanks for the help Write a fun
ID: 3764992 • Letter: N
Question
Need a python script that can run the following, thanks for the help
Write a function pairs1() that takes as inputs a list of integers and an integer target value and returns True if there are two numbers in the list that add up to the target and False otherwise. Your implementation should use the nested loop pattern and check all pairs of numbers in the list.
>>> pairs1([4, 1, 9, 3, 5], 13)
True
>>> pairs1([4, 1, 9, 3, 5], 11)
False
When done, reimplement the function so that it sorts the list first and then efficiently searches for the pair. Analyze the run time of both implementations using the timingAnalysis() app. (Function buildInput() should generate a tuple containing the list and the target.)
Explanation / Answer
Assuming that all the needed has been declared in the main module
for eg (from array import *) which needs to declared in the main body.
The function goes as follows:-
def pairs1(thelist , num)
for i in range(len(thelist)):
j=1
for j in range(len(thelist)) :
a= thelist.index(i)+thelist.index(j)
if(a==num) :
print "true"
else :
print "false"
ALl the keyword defined here have the same meaning as it is.Range will take out the range of the array.
Index finds out the index of the array etc.
Finally the sum of the two number is checked for the target number and hence the output is given.
Reimplementing the function to sort out the array and then finding out.
The logic inside the function is same, we just need to sort the array first.
def pairs1(thelist , num)
thelist.sort()
i=0
for i in range(len(thelist)):
j=1
for j in range(len(thelist)) :
a= thelist.index(i)+thelist.index(j)
if(a==num) :
print "true"
else :
print "false"
The sort() has been used to sort the array which has been passed.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.